今天在开发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详细使用参考链接:https://blog.csdn.net/wwt831208/article/details/54845068
问题原因:
对于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>