1. 程式人生 > >App閃退原因之Your content must have a ListView whose id attribute is 'android.R.id.list' 錯誤

App閃退原因之Your content must have a ListView whose id attribute is 'android.R.id.list' 錯誤

今天在開發Android專案整合推送SDK時,修改layout的頁面配置檔案,在虛擬機器上開啟app直接閃退。

檢視Android Studio 的logcat日誌發現錯誤:Your content must have a ListView whose id attribute is 'android.R.id.list' ,在網上搜索原因後發現,Android專案的MainActivity中,繼承了InstrumentedListActivity ,而此類繼承自ListActivity類,如下圖:

ListActivity是Android中應用較為廣泛的元件,主要用來垂直展示列表項,可以理解為是ListView和Activity的結合。在顯示資料時需要設定對應的介面卡。Adapter常用的有ArrayAdapter、SimpleAdapter和CursorAdapter。

ListActivity的子類主要使用步驟:

1. 繼承ListActivity類,即:MainActivity extends ListActivity

2. 重寫ListActivity類的方法onCreate()方法

    2.1 定義資料:String[] arr ={"a", "b" , "c"};

    2.2 建立對應的介面卡:

          ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout. simple_list_item_1, arr);

為ListView設定介面卡

3. setListAdapter(arrayAdapter);

問題原因:

對於ListActivity類,必須要有一個ListView,由於ListActivity在啟動時會預設去尋找ListView的id,如果不存在,就會如上報錯。

解決方法:

在MainActivity的佈局檔案中新增ListView,並且設定id為list。

即:

<ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
</ListView>

參考連結: