【安卓】为ListView添加空视图emptyView (适于初学者)

一般地,当一个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。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值