我正在尝试使用ListView
,就像在此页面上一样:
http://developer.android.com/resources/tutorials/views/hello-listview.html
我想使用setContentView
,然后使用我在该布局上放置的ListView
。这是我的代码:
public class ListViewTrainingsActivity extends ListActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // It gives me error here?
final String[] COUNTRIES = new String[] {
"Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
"Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
"Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
"Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
"Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
"Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",
"British Virgin Islands"};
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
ListView lv = (ListView) findViewById(android.R.id.list);
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
}
}
我收到的错误是:
E/AndroidRuntime(306): FATAL EXCEPTION: main
E/AndroidRuntime(306): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.yahya.ListViewTrainings/com.yahya.ListViewTrainings.ListViewTrainingsActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
E/AndroidRuntime(306): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
.
.
.
E/AndroidRuntime(306): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
E/AndroidRuntime(306): at android.app.ListActivity.onContentChanged(ListActivity.java:245)
E/AndroidRuntime(306): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:201)
E/AndroidRuntime(306): at android.app.Activity.setContentView(Activity.java:1647)
E/AndroidRuntime(306): at com.yahya.ListViewTrainings.ListViewTrainingsActivity.onCreate(ListViewTrainingsActivity.java:17)
我希望有人能告诉我我做错了什么。
答案 0 :(得分:2)
在您的布局main.xml
中,您必须拥有一个带有ID的ListView
元素(扩展ListActivity
需要此内容):
android:id="@android:id/list"
另外,由于您已扩展ListActivity
课程,因此您可以通过调用getListView()
方法获取ListView
:
ListView lv = getListView();
答案 1 :(得分:2)
如果这有帮助,请使用此android:id="@android:id/list"
检查更改listView ID。