我的程序中new ListView(this) 替换为 findViewById(R.id.listView1) 程序不能运行。
编译都能通过。
请问为什么?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//listView = (ListView) findViewById(R.id.listView1);
listView = new ListView(this);
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getData()));
setContentView(listView);
}
private List<String> getData(){
List<String> data = new ArrayList<String>();
data.add("test1");
data.add("test2");
data.add("test3");
data.add("test4");
return data;
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView1"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
------解决思路----------------------
把这行注释掉:
setContentView(listView);