所以我不确定是否可以在使用构建器的setAdapter 方法在AlertDialog 构建器中设置适配器之后设置SetEmptyView。
但是,我通过在同一个 xml 文件中定义 ListView 和我的空视图(例如 TextView 可见性设置为消失)来解决此问题,例如,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<ListView
android:id="@+id/my_list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:choiceMode="multipleChoice"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"/>
<TextView
android:id="@+id/my_empty_view"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Searching for devices..."
android:layout_gravity="center"
android:textSize="16sp"
android:paddingTop="50dp"
android:paddingBottom="50dp"
android:visibility="gone"/>
</LinearLayout>
我在扩展的DialogFragment 类的OnCreateDialog 方法中扩展了这个视图组(如创建自定义布局 下的documentation 中所述),即,
View myDialogView = inflater.inflate(R.layout.my_dialog_view, null);
从膨胀视图中检索到我的 ListView 和空视图的引用,即,
ListView myListView = (ListView) myDialogView.findViewById(R.id.my_list_view);
TextView myEmptyView = (TextView) myDialogView.findViewById(R.id.my_empty_view);
使用这些设置列表视图setemptyView,即,
myListView.setEmptyView(myEmptyView);
设置我的适配器
myListView.setAdapter(yourAdapter);
然后在构建器中简单地使用setView() 方法
.setView(myDialogView)
这可能是最好的方法。我被 android 文档抛出,它建议在 AlertDialog 构建器中使用 setAdapter 方法。就个人而言,我认为坚持使用setView 方法提供了更大的灵活性。