在android中,listview一般都是通过一个adapter来绑定数据,一般的item的点击事件都会指向同一个目标(intent),只是所带的参数不同而已,但有的时候事与愿违,每个item的目标(intent)是不同的,此时我们需要一点技巧来处理这种情况。。。我的做法是每个item对应的entity添加一个listener ,来监听自己的事件。。上代码:
Listitem的定义[包含了一个onClickListener]
public static class ListItem{ public String text; public String description; public boolean isHeader; public OnClickListener listener; public ListItem(String t,String desc,boolean i,OnClickListener l) { text = t; description = desc; isHeader = i; listener = l; } }初始化一个Arraylist<ListItem>[不同的item对应不同的onClickListener]
private ArrayList<ListItem> initListItems(){ ArrayList<ListItem> listItems = new ArrayList<SettingAdapter.ListItem>( ); listItems.add( new ListItem( "功能",null, true, null) ); listItems.add( new ListItem( "故障诊断设置",null, false, new ItemClickListener( SettingOBDActivity.class ) ) ); listItems.add( new ListItem( "系统",null, true, null) ); listItems.add( new ListItem( "修改密码",null, false,new ItemClickListener( SettingPasswordActivity.class ) )); listItems.add( new ListItem( "时间设置",null, false,new ItemClickListener( Settings.ACTION_DATE_SETTINGS )) ); listItems.add( new ListItem( "蓝牙设置",null, false,new ItemClickListener( Settings.ACTION_BLUETOOTH_SETTINGS )) ); listItems.add( new ListItem( "WIFI设置",null, false,new ItemClickListener( Settings.ACTION_WIFI_SETTINGS )) ); listItems.add( new ListItem( "数据连接设置",null, false,new ItemClickListener( Settings.ACTION_WIRELESS_SETTINGS )) ); listItems.add( new ListItem( "联系客服",null, false, new OnClickListener() { @Override public void onClick(View v) { agent.startFeedbackActivity(); } }) ); listItems.add( new ListItem( "检查更新",MyApplication.getApplication().getAppVersion(), false, new OnClickListener() { @Override public void onClick(View v) { String version = MyApplication.getApplication().getAppVersion(); if(version!=null){ AppUpdateHelper.getInstance( SettingActivity.this ).checkUpdate(version,true); } } }) ); return listItems; }自定义一个clickListener[重构构造方法,或许是你自己的activity,或许是系统的activity]
class ItemClickListener implements OnClickListener{ private Class toActivity; private String toAction; public ItemClickListener(Class activity) { toActivity = activity; } public ItemClickListener(String action){ toAction = action; } @Override public void onClick(View v) { if(toActivity!=null){ Intent toIntent = new Intent(SettingActivity.this,toActivity); startActivityWithAnimation( toIntent ); }else if(toAction!=null){ Intent toIntent = new Intent( toAction ); startActivity( toIntent ); } } }
mListView.setAdapter( adapter ); mListView.setOnItemClickListener( new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { ListItem item = (ListItem) arg0.getAdapter().getItem( arg2 ); if(item.listener!=null){ item.listener.onClick( arg1 ); } } } ); }
listView中adapter有不同的click事件的简单写法,布布扣,bubuko.com
listView中adapter有不同的click事件的简单写法
原文:http://blog.csdn.net/yaya_soft/article/details/25363735