码迷,mamicode.com
首页 > 其他好文 > 详细

ListView之EmptyView

时间:2015-09-09 10:58:29      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

关键字: ListView EmptyView setEmptyView

最新开发一个应用程序,需要用到当ListView为空时设置一些View来显示提示内容。我们已经知道ListView有一个公开的方法:setEmptyView(View v)

可是这个方法的设置是有限制的,就是设置View必需在当前的View hierarchy里,亦即这个View需要被add到当前一个View Tree的一个结点上,如果没有添加到结点上的话,调用setEmptyView(View v)是没有任何效果的。

它的过程大概是:

1
2
3
4
5
ListView listview = (ListView) findViewById(R.id.list);
View emptyView = findViewById(R.id.empty);
ViewGroup parentView = (ViewGroup) listview.getParent();
parentView.addView(newEmptyView, 2); // 你需要在这儿设置正确的位置,以达到你需要的效果。可能还需要正确的LayoutParamater参数
listview.setEmptyView(emptyView);

另:如果你直接设置在XML中也就不需要额外的添加到View Tree中了,因为它已经在那儿了,比如你的Layout是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_vertical"
    android:orientation="vertical" >
    <include layout="@layout/fixed_headerview" />
    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:drawSelectorOnTop="false"
        android:fastScrollEnabled="true"
        android:textSize="18sp" />
    <TextView
        android:id="@+/empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:padding="15dip"
        android:text="@string/text_no_song"
        android:textSize="22sp"
        android:visibility="gone" />
</LinearLayout>

那你只需要以下的代码就可以了:

1
2
3
ListView listview = (ListView) findViewById(R.id.list);
View emptyView = findViewById(R.id.empty);
listview.setEmptyView(emptyView);

ListView之EmptyView

标签:

原文地址:http://www.cnblogs.com/likeju/p/4793784.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!