7.自定义AdapterView的空视图

7.1 问题

要在AdapterView(ListView、GridView等诸如此类的视图)没有数据时显示自定义的视图。

7.2 解决方案

(API Level 1)
把要显示的视图根AdapterView放在同一布局树中,然后调用AdapterView.setEmptyView()自行处理。AdapterView会根据其中ListAdapter的isEmpty()方法的返回值选择显示其自身还是显示空视图。

重点:
一定要将AdapterView和空视图放入布局中,AdapterView仅仅只是变换这两个对象是否可见的参数,而绝对不会在布局树中插入或删除某个视图。

7.3实现机制

下面将一个简单的TextView用作空视图。首先,在布局中放入这两个视图,参见以下代码:
res/layout/empty.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/myempty"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="No Items to Display" />
    <ListView
        android:id="@+id/mylist"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</FrameLayout>

然后在Activity中将空视图的引用提供给ListView,让其进行管理(参见以下代码)。
将空视图链接到列表的Activity

public class EmptyActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.empty);

        ListView list = (ListView)findViewById(R.id.mylist);
        TextView empty = (TextView)findViewById(R.id.myempty);

        /*
         * 附加空试图。
         * 框架将在ListView的Adapter没有元素时显示此视图。
         */
        list.setEmptyView(empty);

        //继续给列表添加Adapter和数据
    }
}

让空视图更有趣
空视图不一定非得是简单无趣的TextView。接下来做点儿对用户更有用的工作,并且在列表为空时添加Refresh按钮(参见以下代码)。
交互式空布局

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:id="@+id/myempty"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="No Items to Display"   />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Tap Here to Refresh" />
    </LinearLayout>

    <ListView
        android:id="@+id/mylist"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

现在,一样是用前面的Activity代码,将一个完整的布局设为空视图,让用户可以对空数据进行一些操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值