我解决我的问题
所有我需要的 - main.xml中的布局和串码 “空” 的标签。 mFavList.setEmptyView(findViewById(android.R.id.empty));
在我的程序fakeFavs是从文本文件填充。 如果文件为空,则正确处理空列表。
也许这对别人有用。工作示例:
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class HelloAndroid3 extends Activity {
/** Called when the activity is first created. */
static final String split_symbol = "\n";
protected ListView mFavList;
protected ArrayList<String> fakeFavs;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fakeFavs = new ArrayList<String>();
this.mFavList = (ListView) this.findViewById(R.id.list_favorites);
refreshFavListItems();
}
private void refreshFavListItems() {
//put some code here that populates fakeFavs
//.......
mFavList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, fakeFavs));
mFavList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mFavList.setEmptyView(findViewById(android.R.id.empty));
//if fakeFavs will be empty, list shows "No Data"
}
}
main.xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="match_parent" >
<ListView android:id="@+id/list_favorites"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
/>
<TextView android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FF0000"
android:text="No Data"/>
尝试初始化'fakeFavs =新的ArrayList()'设置适配器之前。 –
是的,在设置适配器之前,代码中有初始化字符串,但在程序的第一次运行时,fakeFavs(这是用户的联系人列表)必须设置为null,因为列表为空。我需要正确处理空白列表,例如显示“无数据”消息。 – Kenneth
使用fakeFavs.isEmtpy()然后代替fakeFavs ==例如代码空 – MrJre