我在我的Android应用程序中创建了一些复合UI,并且在视图中有一些ListView控件 - 其他控件.因此,我使用"Activity"作为我的活动基类.
现在,当绑定到我的适配器的ListView为空时,我需要显示一条简单的消息,如"No Item".我知道在使用ListActivity时这是可能的,但我不确定这是什么最好的方法?
Jos*_*arl 98
没有一个你可以有一个空视图ListActivity!正确的方法如下
首先在列表下方的布局XML中添加一个"空视图"
...
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<TextView
android:id="@+id/empty"
android:text="Empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
/>
...
Run Code Online (Sandbox Code Playgroud)
接下来覆盖onContentChanged您的活动方法,并将列表的空视图设置为空视图:
@Override
public void onContentChanged() {
super.onContentChanged();
View empty = findViewById(R.id.empty);
ListView list = (ListView) findViewById(R.id.list);
list.setEmptyView(empty);
}
Run Code Online (Sandbox Code Playgroud)
而已!更新适配器时,Android将负责隐藏/显示列表和空视图.
魔法
决定空视图是否显示与否是通过的超类处理ListView,AdapterView.在set适配器上AdapterView注册a DataSetObserver,以便在数据发生更改时通知它.这会触发一个呼叫checkFocus中AdapterView包含以下行
if (mEmptyView != null) {
updateEmptyStatus((adapter == null) || adapter.isEmpty());
}
Run Code Online (Sandbox Code Playgroud)
并根据适配器是否为空来设置空视图可见性.
只需将您ListView与TextView:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="@+id/list"
android:layout_height="fill_parent"
android:layout_width="fill_parent" />
<TextView
android:id="@+id/list_empty"
android:text="No Item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
然后相应地检查项目可见度的项目数ListView:
ListView lv = (ListView)findViewById(R.id.list);
lv.setVisibility((adapter.isEmpty())?View.GONE:View.VISIBLE);
Run Code Online (Sandbox Code Playgroud)
如果您使用自定义适配器,则可以在重写notifyDataSetChanged方法中执行此操作.
| 归档时间: |
|
| 查看次数: |
55426 次 |
| 最近记录: |