安卓开发代码之自定义AdapterView的空视图(2-24)
1.需求:
在AdapterView没有数据时显示自定义的视图。
2.解决方案
把要显示的视图和AdapterView放在同一个布局树中,然后调用AdapterView.setEmptyView()自行处理。AdapterView会根据其中ListAdapter的isEmpty()方法的返回值选择显示其自身还是显示空视图。
注意:一定要将AdapterView和空视图放入布局中,adapterView仅仅只是变换两者是否可见的参数,而绝对不会再布局树中插入或删除某个视图。
3.实现机制:
xml布局:使用一个LinearLayout布局作为空视图,里面含有一个TextView和一个Button。
<FrameLayout
android:id="@+id/frameLayoutId"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/radioGroup1"
android:layout_below="@id/titleId"
android:background="#ffeeeeee" >
<LinearLayout
android:id="@+id/myEmptyLayoutId"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:padding="5dp" >
<TextView
android:id="@+id/emptyTvId"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:gravity="center"
android:text="No Items to Display" />
<Button
android:id="@+id/refreshId"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#ff654321"
android:text="refresh" />
</LinearLayout>
<ListView
android:id="@+id/mylistId"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</FrameLayout>
Java代码:
使用AdapterView.setEmptyView(View v)方法实现,View可以放一个布局或者放一个ProgressBar表示正在加载,可提高用户体验。
/**
* 自定义AdapterView的空视图
* 当ListView中没有数据时显示的自定义空视图。
*/
private void setEmptyListView() {
ListView listView=(ListView) findViewById(R.id.mylistId);
LinearLayout emptyLayout=(LinearLayout) findViewById(R.id.myEmptyLayoutId);
listView.setEmptyView(emptyLayout);
}