在我的项目的整个生命周期中,我一直在努力解决这个问题。我的项目中有很多列表,其中大多数都有标题。我一直在制作一个单独的布局文件并使用 addHeaderView() 将其添加到列表中。问题是当数据(ArrayList,在我的例子中)为空时,标题不会出现。经过几个小时的寻找将标题布局重用为空视图的方法后,我放弃并决定在代码中复制布局并使用 setEmptyView() 将其分配为空视图。问题在于,许多标题包含可单击视图,因此我必须为每个重复的视图加倍所有可单击逻辑。我之前尝试包含标题但失败了,主要是因为我仍然不太明白布局是如何膨胀的等。
最后,我想出了一个解决方案,我想与社区分享,以防其他人遇到类似的问题。我不知道这是否是解决这个问题的最佳方法,任何反馈或建议肯定会受到欢迎。
这是包含列表列表视图的布局的代码:
<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,然后在 onClick 方法中使用单个 id 引用它们:R.id.my_list_button。我需要对此进行更多测试,但它现在似乎有效。我还没有在我的所有列表中实现它,只是在一个列表中实现它,所以它可能无法在所有情况下都起作用。如果您有任何建议,请告诉我,因为这长期以来一直是我的问题。一个问题可能是,如果您想从 ID 实例化按钮,您可能必须再次经历整个过程才能访问正确的 ID?