当你创建一个ListActivity 类来承载一个ListView 对象时,Android可能会抱怨该id 属性的缺失,ListView 。
例如,假设你有一个如下的MainActivity 类:
public class MainActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
然后,你创建了如下的activity_main.xml 布局:
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/list" >
</ListView>
当你构建并运行安卓应用程序时,会发生一个RuntimeException 错误,信息如下:
E/AndroidRuntime: FATAL EXCEPTION: main
# ...
Caused by: java.lang.RuntimeException:
Your content must have a ListView whose id attribute is 'android.R.id.list'
at #...
上面的异常发生是因为ListActivity 类特别需要一个ListView 对象,该对象的id 属性是@android:id/list 。
值@+id/list 解析为R.id.list ,而@android:id/list 解析为android.R.id.list 。
为了解决这个错误,你需要改变你的ListView widget中的android:id 属性,如下所示:
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@android:id/list" >
</ListView>
重建你的应用程序并再次运行它。这一次,错误应该消失。
另外,请注意,ListActivity 类已经在API级别30(Android 11)中被废弃。
当你需要显示一个带有项目列表的UI组件时,建议你使用ListFragment 或RecyclerView 来代替。
现在你已经学会了如何解决ListActivity 类中缺失的android.R.id.list id属性的问题。干得好!👍