我一直在解决这个问题,贯穿我的项目的整个生命周期。我的项目中有很多列表,其中大部分都有标题。我一直在制作一个单独的布局文件,并使用addHeaderView()将它添加到列表中。问题是,当数据(在我的情况下,ArrayList)是空的,头不会出现。经过几个小时寻找一种方法来重新使用头布局作为一个空视图,我放弃了,并决定复制代码中的布局,并使用setEmptyView()将其分配为空视图。问题在于很多头文件包含可点击的视图,所以我必须将所有可重复使用的视图的可点击逻辑加倍。我试图在之前包括标题,但失败了,主要是因为我还不太了解布局是如何膨胀等。Android如何在列表视图中重复使用页眉布局作为空视图
最后,我想出了一个解决方案,我想与社区分享其他人也遇到类似问题。我不知道这是否是解决这个问题的最好方法,任何反馈或建议肯定会受到欢迎。
这里是包含列表列表视图布局代码:
<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/lv_my_list"
style="@style/ListStyle"
android:headerDividersEnabled="false"
/>
<include
layout="@layout/my_list_header"
android:id="@+id/my_list_empty"
/>
</LinearLayout>
的样式定义除其他事项外布局的宽度和高度。
现在我有一个包含标题视图
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/my_list_header"
>
<Button
android:id="@+id/my_list_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Click Me"
/>
</LinearLayout>
我知道的LinearLayout是不是很有效,我使用合并或其他提高效率的措施尝试布局文件,但是这是工作所以第一个版本我现在要和它一起。最后的代码:
// set up the header
myListView = (ListView)findViewById(R.id.lv_my_list);
View header = View.inflate(this, R.layout.my_list_header, null);
Button b = (Button)header.findViewById(R.id.my_list_button);
b.setOnClickListener(this);
myListView.addHeaderView(header);
// set up the empty view
LinearLayout ll = (LinearLayout)findViewById(R.id.my_list_empty);
b = (Button)ll.findViewById(R.id.my_list_button);
b.setOnClickListener(this);
meLocalListView.setEmptyView(ll);
我之所以包裹在一个布局中的按钮是因为我可以设置按钮,以使用这个作为一个OnClickListener然后参照它们两者与单个ID的每个实例:R.我的onClick方法中的id.my_list_button。我需要对此进行更多的测试,但现在似乎仍然有效。我还没有在我的所有名单上实施它,只是一个,所以它可能无法在所有情况下工作。如果您有任何建议,请让我知道,因为这对我来说长期以来一直是个问题。一个问题可能是,如果你想从ID实例化按钮,你可能不得不再次通过整个过程来访问正确的ID?
这里是解决方案 - > http:// stackoverflow。com/a/34557372/542532 – Sadegh 2016-01-01 15:23:26