一般地,当一个APP首次启动时,ListView中还没有内容可以用来显示,手机屏幕上一片空白、没有操作提示,不利于用户操作。此时,可以利用ListView支持的“空视图”功能来定制并显示我们的“欢迎画面”。具体实现方法如下:
创建xml布局文件,定义2个视图,第一个是ListView,id是@android:id/list(系统预先定义的);第二个是所谓的“空视图”,就是我们自己定义的视图布局,可以是简单的一个TextView,也可以是定制的LinearLayout之类,但id必须是@android:id/empty。Android系统会自动处理这2个具有特殊id的视图,当ListView没有内容时,自动调用id为@android:id/empty的视图;否则,调用id为@android:id/list的视图。
xml文件:
<?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"
android:paddingLeft="8dp"
android:paddingRight="8dp" >
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<LinearLayout
android:id="@id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="120dp"
android:layout_marginBottom="60dp"
android:layout_gravity="center"
android:text="@string/list_fragment_empty_text" />
<Button
android:id="@+id/button_add_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/new_crime" />
</LinearLayout>
</LinearLayout>
布局文件里,配置了一个线性布局,包含一个TextView显示一行提示文字、和一个按钮(添加ListView内容)。
ListView java代码:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
// View v = super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.list_fragment_empty, container, false);
Button button = (Button)v.findViewById(R.id.button_add_item);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//这里添加按钮相应代码
}
});
if(mSubtitleVisible) {
getActivity().getActionBar().setSubtitle(R.string.subtitle);
}
return v;
}
在onCreateView()中inflate布局,同时设置处理按钮响应的Listener。