MainActivity.java
package com.example.ch02_listview;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private String[] mListStr={"小胡","男","19","杭州","[email protected]","15757188543"};
ListView mListView=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView=getListView();
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mListStr));
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> adapterView,View view,int position,long id) {
Toast.makeText(MainActivity.this,"你選擇了:"+mListStr[position],Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
你這個是繼承的ListActivity, getListView()是ListActivity的方法,這裡沒問題
問題應該是在onCreate方法裡setContentView(R.layout.activity_main); 這一行,既然用了ListActivity就已經有了一個默認布局了,直接刪掉這一行,書裡應該沒有這一行吧
activity_main這個布局文件如果沒地方用到也可以刪了