我正在上课,如下所示
// All necessary imports are here
public class More extends Activity {
String[] MoreItems = { "Transfers", "Budgets", "Branches", "Tools", "News",
"Customer Service", "Settings", "Help", "About" };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.more_view);
ListView moreListView = (ListView) findViewById(R.id.moreListView);
MoreListAdapter listAdapter = new MoreListAdapter();
moreListView.setAdapter(listAdapter);
// accountsTypeListView.setOnItemClickListener(listClickListner);
}
class MoreListAdapter extends ArrayAdapter<String> {
MoreListAdapter() {
super(More.this, R.layout.list_item, MoreItems);
}
public View getView(int position, View convertView, ViewGroup parent) {
View row;
if (convertView == null) {
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.list_item, parent, false);
} else {
row = convertView;
}
TextView tv = (TextView) row.findViewById(R.id.textItem);
tv.setText(getItem(position));
return row;
}
}
}
它会生成列表,我想在各自的点击中调用各自的活动,比如如果用户点击传输然后它会显示传输活动, 如何在此列表上调用 onClickListener 以及如何在单击时启动 Activity。
你也可以这样做..
moreListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Log.d("############","Items " + MoreItems[arg2] );
}
});
有两个选项可以处理每一行的点击事件。
1)如果你的类扩展了
ListActivity
,你可以重写下面的方法。
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//do something here using the position in the array
}
2)在
getView()
方法中处理行的点击事件
row.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
}
});
例如:
ListView lv = getListView();
lv.setAdapter(listAdapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Intent i = new Intent(More.this, NextActvity.class);
//If you wanna send any data to nextActicity.class you can use
i.putExtra(String key, value.get(position));
startActivity(i);
}
});
您的“更多”类必须扩展 ListActivity 而不是 Activity,然后您可以覆盖 onListItemClick
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//do something here using the position in the arrya
}
编辑: 忘了说,在您的布局中,您的 ListView 必须被调用:android:id="@android:id/list"