在移动平台常常用列表来显示数据,这时,我们要考虑两种情况:有数据供我们展示和没有数据,比如用ListView,我们怎么处理空列表的情况呢?
ListView以及其他的列表继承自AdapterView,AdapterView中有一个方法setEmptyView(View view)处理空数据,AdapterView实例化时,如果Adapter为空,就会调用这个方法。
效果图:
演示下此方法的用法:
布局xml代码:用FrameLayout使两个控件叠加
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/my_list_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<ImageView
android:id="@+id/empty_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/empty_view" />
</FrameLayout>
主代码:
package com.manning.androidhacks.hack024;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class MainActivity extends Activity {
private ListView mListView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 初始化mListView
mListView = (ListView) findViewById(R.id.my_list_view);
// 把empty_view设置为mListView的数据为空时的view
mListView.setEmptyView(findViewById(R.id.empty_view));
}
}
数据为空的时,我们常常隐藏掉ListView,用setEmptyView(View view),代码会更紧凑和易读,更好的优化是用ViewSub来加载这个 view,当不需要时,将不会绘制,节省时间和资源