转自http://www.eoeandroid.com/code/2011/1229/525.html
listview在android中是一个非常普通的组件,通常我们都是这样用的(如你并非这样,那么恭喜你,你有优秀程序员的潜力):
01 | <font face= "'Times New Roman'" ><font color= "#000000" > |
02 | this .setListAdapter(newArrayAdapter<String>( this , |
03 | android.R.layout.simple_list_item_1, |
04 | newString[]{ "list1" , "list2" , "list3" })); |
08 | protected voidonListItemClick(ListView l, View v, int position, long id) { |
10 | Intent i= new Intent(); |
14 | i.setClass(ListTest. this , List1. class ); |
18 | i.setClass(ListTest. this , List2. class ); |
22 | i.setClass(ListTest. this , List3. class ); |
30 | super .onListItemClick(l, v, position,id); |
这个不必多说,再看实现同样的功能google实现的代码:
1 | setListAdapter( new SimpleAdapter( this , getData(), android.R.layout.simple_list_item_1, new String[]{ "title" }, new |
2 | int []{android.R.id.text1})); |
3 | getListView().setTextFilterEnabled( true ); |
这里的adpter填充数据是取自getData()这个方法,如下:
02 | private List getData(){ |
03 | List<Map>dataList= new ArrayList<Map>(); |
04 | Intentintent= new Intent(Intent.ACTION_MAIN, null ); |
05 | intent.addCategory(Intent.CATEGORY_SAMPLE_CODE); |
06 | PackageManagerpManager=getPackageManager(); |
07 | List<ResolveInfo>list=pManager.queryIntentActivities(intent, 0 ); |
13 | Log.i( "len===" , String.valueOf(len)); |
15 | for ( int i = 0 ; i < len;i++) { |
16 | ResolveInfoinfo=list.get(i); |
17 | CharSequencelable=info.loadLabel(pManager); |
19 | if ( "com.android.test" .equals(info.activityInfo.applicationInfo.packageName)) { |
20 | addItem(dataList, lable.toString(), myIntent(info.activityInfo.applicationInfo.packageName, |
21 | info.activityInfo.name)); |
再看addItem()方法:
01 | private void addItem(List<Map> data,Stringname,Intent intent){ |
02 | Map<String,Object> map= new HashMap<String, Object>(); |
03 | map.put( "title" , name); |
04 | map.put( "intent" , intent); |
08 | private Intent myIntent(StringcontentPkg,String toPkg){ |
10 | i.setClassName(contentPkg,toPkg); |
16 | void onListItemClick(ListView l, View v, int position, long id) { |
17 | Mapmap=(Map) l.getItemAtPosition(position); |
18 | Intentintent=(Intent) map.get( "intent" ); |
19 | startActivity(intent); |
在这里,代码量似乎是多了不少,很多一步直接写上的都用方法封装起来,看起来很零碎但却非常独立,可塑性非常强,如:一旦为listview添加新的item的话,只需要重新写一个跳转后的类该代码段会自动识别并实现跳转,无需为adapter重新填充,可以说这段代码无需改动而能实现任何数量的listview的添加,当然你要为此写上跳转的目的类,且这个目的类要标记为.
1 | <action android:name= "android.intent.action.MAIN" /> |
3 | android:name= "android.intent.category.SAMPLE_CODE" /> |
这是google源码里涉及到的,我将其中涉及到listview部分简化出来以便大家专注研究严谨精炼的代码是怎么构造出来的,呵呵,源码是个好东西,希望大家多抽时间看看,为便于大家比较优虐,我将上面的两个源码贴出来:
http://www.eoe.cn/uploadfile/2011/1229/20111229103249289.rar
http://www.eoe.cn/uploadfile/2011/1229/20111229103250197.rar