【问题标题】:How to check if EmptyView of my ListView is shown in Android?如何检查我的 ListView 的 EmptyView 是否显示在 Android 中?
【发布时间】:2012-10-22 13:42:20
【问题描述】:

我正在使用 ListView,如果列表为空,我会显示 EmptyView。如何检查此视图是否显示为布尔变量?

这里是我的 ListView 的代码:

deviceList = (ListView) findViewById(R.id.DeviceList);
ListAdapter listenAdapter = new ArrayAdapter(this,
                android.R.layout.simple_list_item_2, deviceArray);

//add a view which is shown if the ListView is empty
deviceList.setEmptyView( findViewById( R.id.empty_list_view ) );
deviceList.setAdapter(listenAdapter);

【问题讨论】:

  • 看看ListView的适配器是null还是里面有值。
  • 我该怎么做? ListAdapter 没有这样的方法,这里是Android开发者页面的链接developer.android.com/reference/android/widget/ListAdapter.html
  • 您使用超类(在这种情况下为接口),但您的适配器是ArrayAdapter,所以使用它。示例:boolean isEmptyViewShown = ((ArrayAdapter) deviceList.getAdapter() == null) || (((ArrayAdapter) deviceList.getAdapter()).getCount() == 0);
  • 我尝试了您的代码,但即使我将项目添加到列表中,布尔变量也始终为真。你知道为什么吗?
  • 您必须在 将项目添加到列表后运行该代码(或在需要了解视图状态时运行它),即 boolean 变量不会自行更新。

标签: android listview listadapter


【解决方案1】:

您可以使用“特殊”android id 在 xml 中执行此操作。如果您在布局 xml 文件中使用此代码,则空文本会在需要时自动显示:

<ListView android:layout_height="wrap_content" android:layout_width="match_parent"    android:id="@id/android:list"/>
<TextView android:layout_height="wrap_content" android:layout_width="match_parent"   android:text="@string/no_tasks" android:id="@id/android:empty"
android:gravity="center_vertical|center_horizontal"/>

android:empty id 的 textview 仅在 android:list 组件为空时显示。

希望对你有帮助。

【讨论】:

  • 这不是我的问题,我已经可以显示空列表了。但是如果显示空列表,我想要一个布尔变量,它具有“true”
  • 啊,确实,抱歉。我需要 RTFQ ;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多