如何使用自定义行和标题布局预览Android ListView

40

我曾经多次使用自定义布局创建带有标题和行项目的列表视图,但总是会让我恼火的是Android Studio中的UI预览不能显示预览。显然,这是因为ListView或CursorAdapter通过编程方式加载自定义布局,但如果我想以某种方式在xml中指定标题和页脚布局,以便查看预览怎么办?有人知道如何做吗?


4
你尝试过使用 tools:listitem 吗? - Salem
@Salem 很有趣。这在我的自动完成中没有显示,但它确实有效。谢谢。如果您将其发布为答案,我会接受它。 - startoftext
2个回答

105

您可以使用tools:listitem。只需在布局的根中添加tools命名空间即可。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    (...)

接着在你的ListView中设置列表项的布局

 <ListView
    android:id="@+id/mylistView"
    tools:listitem="@layout/my_list_item"
    (...)

还可以使用listheader/listfooter来设置页眉/页脚。


2
在右侧视图中,是否有可能删除“项目1”、“项目2”? - Antonio Sesto
14
原文:turns out in Android Studio, the listview needs to have an id attribute set before the listitem preview will show up.翻译:在Android Studio中,原来需要为listview设置一个id属性后,列表项预览才会出现。 - Maks
谢谢 @Maks,你帮我省了很多麻烦。 - woodii

2

xmlns:tools="http://schemas.android.com/tools" 命名空间用于开发目的(预览),不会编译进应用程序中。

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:listfooter="@layout/item_footer"
    tools:listheader="@layout/item_header"
    tools:listitem="@layout/item" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接