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代码,将一个完整的布局设为空视图,让用户可以对空数据进行一些操作。

Demo下载地址:
1.7 自定义AdapterView的空视图

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容