Android在ListView为空时显示文本 [英] Android displaying text when ListView is empty

查看:73
本文介绍了Android在ListView为空时显示文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将ID为@android:id/emptyTextView设置为在ListView中没有任何项目时显示一条消息.但是,即使ListView中有项目,该TextView也会在项目显示之前显示.

I'm setting a TextView with the id @android:id/empty to display a message when there are no items in the ListView. However, this TextView gets displayed even if there are items in the ListView, right before the items show up.

如何使它仅在ListView中没有任何元素时才显示?

How can I make it such that it only gets displayed when there are no elements in the ListView?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

<ListView
    android:id="@android:id/list"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:dividerHeight="1dp" >
</ListView>

<TextView 
    android:id="@android:id/empty"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/empty_list" />

</LinearLayout>

PS:我正在使用LoaderSimpleCursorAdapterListFragment.

PS: I'm using a Loader and a SimpleCursorAdapter with a ListFragment.

推荐答案

我猜您正在使用包含ListView的常规FragmentActivity.如果是这样,则必须将空白布局手动添加到ListView.

I'm guessing you are using a regular Fragment or Activity with a ListView inside of it. If you are, you must add the empty layout to the ListView manually.

例如

ListView lv = (ListView)findViewById(android.R.id.list);
TextView emptyText = (TextView)findViewById(android.R.id.empty);
lv.setEmptyView(emptyText);

然后,ListView的适配器为空时将自动使用此视图

Then your ListView will automatically use this view when its adapter is empty

如果您使用的是ListActivity,则无需在ListView上调用setEmptyView(),因为ListActivity会自动为您管理.

If you are using a ListActivity you do not need to call setEmptyView() on the ListView since the ListActivity automatically manages that for you.

这篇关于Android在ListView为空时显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆