【问题标题】:How do I display a TextView when a ListView is empty?ListView 为空时如何显示 TextView?
【发布时间】:2013-11-11 15:34:34
【问题描述】:

我有一个返回 ListView 的 ListFragment。如果列表中没有项目,我想显示一个替代的 TextView 。假设您可以在 XML 中添加一个 TextView android:id="@android:id/empty" 元素。

但是……

添加包含 ListView 和 TextView 的 FrameLayout 可以预见地给我 “FrameLayout 无法转换为 ListView”

我也不能添加一个 TextView 元素。 “文档中根元素之后的标记必须格式正确。”

而且我不能切换到 View 而不是 ListView 因为它不再是一个列表。

...我该怎么做呢?

代码:

    @Override
public View onCreateView ( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {

    adapter = new ArrayAdapter<Project> ( getActivity (), android.R.layout.simple_list_item_1 );
    arrayList = ProjectManager.getProjectList ( getActivity () );
    for ( Project p : arrayList ) {
        if ( p.getStatus () == Project.ONGOING ) {
            adapter.add ( p );
        }
    }

    ListView listView = ( ListView ) inflater.inflate ( R.layout.list, container, false );
    listView.setAdapter ( adapter );

    return listView;
}

XML:

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

【问题讨论】:

    标签: android listview view android-listfragment fragmentstatepageradapter


    【解决方案1】:

    我有一个返回 ListView 的 ListFragment。如果列表中没有项目,我想显示一个替代的 TextView 。假设您可以在 XML 中添加一个 TextView android:id="@android:id/empty" 元素。

    你可以。

    添加包含 ListView 和 TextView 的 FrameLayout 可以预见地给我“FrameLayout 不能转换为 ListView”。

    这是因为您的代码中存在错误,您假设inflate() 的结果是ListView。将其更改为使用findViewById()找到在膨胀布局中的ListView

    【讨论】:

    • 我尝试了以下方法,但这给了我“指定的孩子已经有父母”。代码:“ListView listView = (ListView) inflater.inflate(R.layout.list_projects_ongoing, container, false).findViewById (R.id.listView);”
    • @CaptainHindsight:那条线不会给你那个错误。其他东西可能,但不是那条线。此外,您需要从onCreateView() 返回inflate() 的结果,在您的情况下,您不能这样做,因为您将丢弃inflate() 结果。
    【解决方案2】:

    添加一个 id 为空的 TextView:

    <TextView android:id="@android:id/empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/emptyt_message" />
    

    到相同的布局

    【讨论】:

      【解决方案3】:

      请看下面的方法:

      http://developer.android.com/reference/android/widget/AdapterView.html#setEmptyView(android.view.View)

      为了使这个有用,您的片段应包含一个容器(即FrameLayout),其中包含ListViewTextView 以及您的空消息。

      在扩展布局时,指定文本视图的视图 ID。将此文本视图的初始可见性设置为INVISIBLE。文本视图的可见性会根据适配器中的元素数量自动更新。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多