Android 当listview为空时,在listview底部添加一个按钮(使用ListActivity)

Android 当listview为空时,在listview底部添加一个按钮(使用ListActivity),android,listview,layout,Android,Listview,Layout,当列表为空时,我使用extends ListActivity显示空消息。 下面是我的xml文件: <?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"

当列表为空时,我使用extends ListActivity显示空消息。 下面是我的xml文件:

<?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:orientation="vertical"    >

    <ListView android:id="@+id/android:list"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_weight="1.0">
    </ListView>

    <TextView android:id="@android:id/empty"
               android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:text="No Items! Please Add!"/> 

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"        
        android:text="Add Item" />

</LinearLayout>


我的问题是,该按钮只能在列表中有项目时显示,但在列表为空时无法显示。当列表为空时,该按钮如何显示?

只需使用
android
标记即可
android:visible
按钮
可在
xml
中设置的代码参考id

button.setVisibility(View.Visible or View.inVisible) based on your requirement.

您应该在listview的布局中创建页脚视图布局

View footer = ((LayoutInflater) ActivityContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer, null, false);

ListView.addFooterView(footer);

同时检查。

您可以通过执行以下操作来检查ListView中是否没有项目

listview.getAdapter().isEmpty

如果是,请将按钮的可见性设置为
消失
。否则,
可见
首先检查
getCount()
。如果
getCount()
返回0,则按钮的
可见性应该是可见的,否则
不可见的
消失的

好吧,我不想添加页脚,只需要添加一个按钮。我将xml更改如下,然后问题就解决了。谢谢大家^^

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

    <ListView android:id="@+id/android:list"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_weight="1.0"
          android:layout_above="@+id/bAdd">
    </ListView>


    <TextView android:id="@android:id/empty"
               android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:layout_above="@+id/bAdd"
               android:text="No Items! Please Add!"/> 

     <Button
        android:id="@+id/bAdd"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"        
        android:text="Add Item" />



</RelativeLayout>

您可以动态检查列表中是否存在要显示的元素,如果不存在,则将可见性设置为“消失”。