Android常用适配器分析(如何制作简易Launcher)

Android常用适配器分析

     Android中适配器是连接后端数据和前端显示的适配器接口,是数据和UI之间重要的纽带。系统中常见的View有ListView、GridView都要用到Adapter.列表控件是扩展了android.widget.AdapterView的类,包括ListView、GridView、Spinner和Gallery。而AdapterView本身实际上扩展了android.widget.ViewGroup,这意味着ListView、GridView等都是容器控件,换句话说列表控件包含一组视图,适配器的用途是Adapter管理数据,并为其提供子视图。

下图是我在网上找到的比较全的Android适配器结构图:

 

     这里面最常用的几个布局是ArrayAdapter、SimpleAdapter、CursorAdapter以及BaseAdapter。其中BaseAdapter是一个抽象类,需要子类继承并实现其中的接口才能使用,常用于用户自定义显示比较复杂的数据。

1)ArrayAdapter<T>

     ArrayAdapter数组适配器是Android中最简单的适配器,专门用于显示列表控件。常用构造方法如下:

     public ArrayAdapter(Context context, int textViewResourceId, List<T> objects);

     public ArrayAdapter(Context context, int textViewResourceId, T[] objects);

Demo1:

[html]  view plain copy print ?
  1. public class MainActivity extends Activity {  
  2.   
  3.     private ListView listView;  
  4.       
  5.     @Override  
  6.     protected void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8. //      setContentView(R.layout.activity_main);  
  9.         String[] strings = {"1", "2", "3", "4", "5"};  
  10.         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item1, strings);  
  11.         listView = new ListView(this);  
  12.         listView.setAdapter(adapter);  
  13.         setContentView(listView);  
  14.     }  
  15. }  

 注意:这里资源上针对子布局资源ID的前缀为android,意味着系统不在本地/res目录中查找,会在系统自己的目录中查找。位于SDK文件的platforms/android-version/data/res/layout目录下,我们找到simple_list_item1.xml,其实际内容如下:

[html]  view plain copy print ?
  1. <TextView xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:id="@android:id/text1"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:textAppearance="?android:attr/textAppearanceListItemSmall"  
  6.     android:gravity="center_vertical"  
  7.     android:paddingStart="?android:attr/listPreferredItemPaddingStart"  
  8.     android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"  
  9.     android:minHeight="?android:attr/listPreferredItemHeightSmall"  
  10. />  

  这里strings可以是一个字符串数组,也可以是一个List集合。如:

[html]  view plain copy print ?
  1. private List<String> getData() {  
  2.     List<String> data = new ArratList<String>();  
  3.     data.add("one");  
  4.     data.add("two");  
  5.     data.add("three");  
  6.     data.add("four");  
  7.     data.add("three");  
  8.     return data;  
  9. }  

 

   在代码中我们的Activity可以直接继承于ListActivity,ListActivity类继承与Activity类,默认绑定了一个ListView界面组件,并提供一些与列表视图、处理相关的操作。

Demo2:

    

[html]  view plain copy print ?
  1. public class MainActivity extends ListActivity {  
  2.   
  3.     private ListView listView;  
  4.       
  5.     @Override  
  6.     protected void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.           
  9.         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item1, getData());  
  10.         setListAdapter(adapter);  
  11.     }  
  12.       
  13.     private List<String> getData() {  
  14.         List<String> data = new ArrayList<String>();  
  15.         data.add("one");  
  16.         data.add("two");  
  17.         data.add("three");  
  18.         return data;  
  19.     }  
  20.   
  21. }  

 

2)SimpleAdapter

     simpleAdapter的扩展性最好,可以定义各种各样的布局,添加ImageView、Button、CheckBox等。

Demo:

     simple_list.xml

[html]  view plain copy print ?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:orientation="horizontal" >  
  6.   
  7.     <TextView  
  8.         android:id="@+id/textView"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_margin="20dp"  
  12.         android:textIsSelectable="true" >  
  13.     </TextView>  
  14.   
  15.     <ImageView  
  16.         android:id="@+id/img"  
  17.         android:layout_width="wrap_content"  
  18.         android:layout_height="wrap_content"  
  19.         android:layout_margin="20sp" >  
  20.     </ImageView>  
  21.   
  22. </LinearLayout>  

     MainActivity.java

 

[html]  view plain copy print ?
  1. public class MainActivity extends ListActivity {  
  2.   
  3.       
  4.     @Override  
  5.     protected void onCreate(Bundle savedInstanceState) {  
  6.         // TODO Auto-generated method stub  
  7.         super.onCreate(savedInstanceState);  
  8.           
  9.         String [] strings = new String[] {"title", "img"};  
  10.         int[] ids = new int[] {R.id.textView, R.id.img};  
  11.         SimpleAdapter adapter = new SimpleAdapter(this, getData(), R.layout.simple_list, strings, ids);  
  12.         setListAdapter(adapter);  
  13.     }  
  14.       
  15.     private List<Map<String, Object>> getData() {  
  16.         List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();  
  17.         Map<String, Object> map = new HashMap<String, Object>();  
  18.         map.put("title", "Hello");  
  19.         map.put("img", R.drawable.iag);  
  20.         list.add(map);  
  21.         map = new HashMap<String, Object>();  
  22.         map.put("title", "world");  
  23.         map.put("img", R.drawable.ic_launcher);  
  24.         list.add(map);  
  25.         return list;  
  26.     }  
  27. }  

 

3)CursorAdapter

    一般要以数据库为数据源的时候才会使用SimpleCursorAdapter.这个适配器也需要在ListView中使用,通过游标向列表提供数据。

Demo:

[html]  view plain copy print ?
  1. @Override  
  2. protected void onCreate(Bundle savedInstanceState) {  
  3.     // TODO Auto-generated method stub  
  4.     super.onCreate(savedInstanceState);  
  5.       
  6.     Cursor  cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null);  
  7.     startManagingCursor(cursor);  
  8.     ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.simple_list, cursor,   
  9.             new String[] {People.NAME}, new int[] {R.id.textView});  
  10.     setListAdapter(adapter);  
  11. }  

 

4)BaseAdapter

   一般用于显示复杂的列表布局,由于BaseAdapter是一个抽象类,使用该类需要自己写一个适配器继承于该类,并重新一些方法。

   如下Demo我们通过ApplicationInfoAdapter继承于BaseAdapter,实现一个简单的Launcher,通过PackageManager查询系统中Intent.ACTION_MAIN和Intent.CATEGORY_LAUNCHER的Activity并将其通过ListView的形式显示出来,然后点击某一项进入相应的Activity。

首先我们定义一个描述应用程序的类AppInfo:

[html]  view plain copy print ?
  1. public class AppInfo {  
  2.     private String appLabel;    // 应用程序标签  
  3.     private Drawable appIcon;   // 应用程序 的图像  
  4.     private Intent intent;    
  5.     private String pkgName;     // 应用程序所对应包名  
  6.     private Context context;  
  7.       
  8.     public AppInfo(Context context) {  
  9.         this.context = context;  
  10.     }  
  11.       
  12.     public String getAppLabel() {  
  13.         return appLabel;  
  14.     }  
  15.     public void setAppLabel(String appName) {  
  16.         this.appLabel = appName;  
  17.     }  
  18.       
  19.     public Drawable getAppIcon() {  
  20.         return appIcon;  
  21.     }  
  22.       
  23.     public void setAppIcon(Drawable appIcon) {  
  24.         this.appIcon = appIcon;  
  25.     }  
  26.       
  27.     public Intent getIntent() {  
  28.         return intent;  
  29.     }  
  30.       
  31.     public void setIntent(Intent intent) {  
  32.         this.intent = intent;  
  33.     }  
  34.       
  35.     public String getPkgName() {  
  36.         return pkgName;  
  37.     }  
  38.       
  39.     public void setPkgName(String pkgName) {  
  40.         this.pkgName = pkgName;  
  41.     }  
  42. }  

      然后我们定义一个ApplicationInfoAdapter 继承于BaseAdapter,并重写其getCount(),getItem(),getItemId(),getView()等函数。

[html]  view plain copy print ?
  1. public class ApplicationInfoAdapter extends BaseAdapter {  
  2.   
  3.     private static final String TAG = "ApplicationInfoAdapter";  
  4.     private List<AppInfo> mListAppInfo = null;  
  5.     LayoutInflater infater = null;  
  6.       
  7.     public ApplicationInfoAdapter(Context context, List<AppInfo> apps) {  
  8.         // TODO Auto-generated constructor stub  
  9.         infater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  10.         mListAppInfo = apps;  
  11.     }  
  12.       
  13.     @Override  
  14.     public int getCount() {  
  15.         // TODO Auto-generated method stub  
  16.         Log.i(TAG, "size="+mListAppInfo.size());  
  17.         return mListAppInfo.size();  
  18.     }  
  19.   
  20.     @Override  
  21.     public Object getItem(int arg0) {  
  22.         // TODO Auto-generated method stub  
  23.         return mListAppInfo.get(arg0);  
  24.     }  
  25.   
  26.     @Override  
  27.     public long getItemId(int arg0) {  
  28.         // TODO Auto-generated method stub  
  29.         return 0;  
  30.     }  
  31.   
  32.     @Override  
  33.     public View getView(int position, View convertView, ViewGroup viewGroup) {  
  34.         // TODO Auto-generated method stub  
  35.         Log.i(TAG, "getView at" + position);  
  36.         View view = null;  
  37.         ViewHolder holder = null;  
  38.           
  39.         if(convertView == null || convertView.getTag()==null) {  
  40.             view = infater.inflate(R.layout.app_list, null);  
  41.             holder = new ViewHolder(view);  
  42.             view.setTag(holder);  
  43.         } else {  
  44.             view = convertView;  
  45.             holder = (ViewHolder)convertView.getTag();  
  46.         }  
  47.           
  48.         AppInfo appInfo = (AppInfo)getItem(position);  
  49.         holder.appIcon.setImageDrawable(appInfo.getAppIcon());  
  50.         holder.tvAppLabel.setText(appInfo.getAppLabel());  
  51.         holder.tvPktName.setText(appInfo.getPkgName());  
  52.         return view;  
  53.     }  
  54.       
  55.     class ViewHolder {  
  56.         ImageView appIcon;  
  57.         TextView tvAppLabel;  
  58.         TextView tvPktName;  
  59.           
  60.         public ViewHolder(View view) {  
  61.             this.appIcon = (ImageView)view.findViewById(R.id.imgApp);  
  62.             this.tvAppLabel = (TextView)view.findViewById(R.id.tvAppLabel);  
  63.             this.tvPktName = (TextView)view.findViewById(R.id.tvPkgName);  
  64.         }  
  65.     }  
  66. }  

    这里我们通过LAYOUT_INFLATER_SERVICE布局管理器服务动态加载app_list.xml用来显示每一个应用程序的信息

[html]  view plain copy print ?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="50dp"  
  5.     android:orientation="horizontal" >  
  6.       
  7.     <ImageView android:id="@+id/imgApp"  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="fill_parent">  
  10.     </ImageView>  
  11.       
  12.     <RelativeLayout   
  13.         android:layout_width="fill_parent"  
  14.         android:layout_height="40dp"  
  15.         android:layout_marginLeft="10dp">  
  16.           
  17.         <TextView android:id="@+id/tvLabel"  
  18.             android:layout_width="wrap_content"  
  19.             android:layout_height="wrap_content"  
  20.             android:text="AppLabel:">  
  21.         </TextView>  
  22.           
  23.         <TextView android:id="@+id/tvAppLabel"  
  24.             android:layout_width="wrap_content"  
  25.             android:layout_height="wrap_content"  
  26.             android:layout_marginLeft="3dp"  
  27.             android:text="Label"  
  28.             android:layout_toRightOf="@id/tvLabel"  
  29.             android:textColor="#ffD700">  
  30.         </TextView>  
  31.           
  32.         <TextView android:id="@+id/tvName"  
  33.             android:layout_width="wrap_content"  
  34.             android:layout_height="wrap_content"  
  35.             android:layout_below="@id/tvLabel"  
  36.             android:text="包名">  
  37.         </TextView>  
  38.   
  39.         <TextView android:id="@+id/tvPkgName"  
  40.             android:layout_width="wrap_content"  
  41.             android:layout_height="wrap_content"  
  42.             android:layout_below="@id/tvAppLabel"  
  43.             android:layout_alignLeft="@id/tvAppLabel"  
  44.             android:textColor="#ffD700">  
  45.         </TextView>  
  46.     </RelativeLayout>"  
  47. </LinearLayout>  

然后我们在MainActivity中通过PackageManager查询系统中所有的ACTION_MAIN和 CATEGORY_LAUNCHER的属性的Activity,通过ApplicationInfoAdapter适配器显示到ListView上。

[html]  view plain copy print ?
  1. public class MainActivity extends Activity implements OnItemClickListener {  
  2.   
  3.     private static final String LOG_TAG = "MainActivity";  
  4.     private static final int MSG_SUCCESS = 0;  
  5.       
  6.     private ListView listView = null;  
  7.     private List<AppInfo> mListAppInfos = null;  
  8.     Handler mHandler = null;  
  9.       
  10.     @Override  
  11.     protected void onCreate(Bundle savedInstanceState) {  
  12.         super.onCreate(savedInstanceState);  
  13.         setContentView(R.layout.activity_main);  
  14.           
  15.         listView = (ListView) this.findViewById(R.id.listView);  
  16.         mListAppInfos = new ArrayList<AppInfo>();  
  17.   
  18.         mHandler = new Handler() {  
  19.             public void handleMessage(android.os.Message msg) {  
  20.                 switch (msg.what) {  
  21.                 case MSG_SUCCESS:  
  22.                     ApplicationInfoAdapter applicationInfoAdapter = new ApplicationInfoAdapter(  
  23.                             MainActivity.this, mListAppInfos);   
  24.                     listView.setAdapter(applicationInfoAdapter);  
  25.                     listView.setOnItemClickListener(MainActivity.this);  
  26.                     break;  
  27.   
  28.                 default:  
  29.                     break;  
  30.                 }  
  31.             };  
  32.         };  
  33.           
  34.         new Thread(new Runnable() {  
  35.               
  36.             @Override  
  37.             public void run() {  
  38.                 // TODO Auto-generated method stub  
  39.                 queryAppInfo(); // 查询所有应用程序信息  
  40.                 mHandler.obtainMessage(MSG_SUCCESS).sendToTarget();  
  41.             }  
  42.         }).start();  
  43.     }  
  44.   
  45.     public void queryAppInfo() {  
  46.           
  47.         PackageManager pm = this.getPackageManager();  
  48.   
  49. /*      List<ApplicationInfo> listApplications = pm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);  
  50.         Collections.sort(listApplications, new ApplicationInfo.DisplayNameCoamparator(pm));  
  51.         for(ApplicationInfo app : listApplications) {  
  52.             if((app.flags & ApplicationInfo.FLAG_SYSTEM) > 0) {  // 系统程序  
  53.   
  54.             } else if( (app.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) { // 第三方程序  
  55.                   
  56.             } else if((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) { // 系统程序被用户更新了  
  57.                   
  58.             } else if((app.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {   // 安装在SD卡程序  
  59.                   
  60.             }  
  61.         }*/  
  62.           
  63.           
  64.         Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);  
  65.         mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);  
  66.           
  67.         // 查询获得所有ResolveInfo对象  
  68.         List<ResolveInfo> resolveInfos = pm.queryIntentActivities(mainIntent, PackageManager.MATCH_DEFAULT_ONLY);  
  69.           
  70.         for(ResolveInfo reInfo : resolveInfos) {  
  71.             Log.e(LOG_TAG, "name:"+reInfo.activityInfo.name + "pkg:"+reInfo.activityInfo.packageName);  
  72.         }  
  73.           
  74.         // 根据name排序  
  75.         Collections.sort(resolveInfos, new ResolveInfo.DisplayNameComparator(pm));  
  76.           
  77.         for(ResolveInfo reInfo : resolveInfos) {  
  78.             Log.e(LOG_TAG, "name:"+reInfo.activityInfo.name + "pkg:"+reInfo.activityInfo.packageName);  
  79.         }  
  80.           
  81.         if(mListAppInfos != null) {  
  82.               
  83.             mListAppInfos.clear();  
  84.           
  85.             for(ResolveInfo reInfo : resolveInfos) {  
  86.                   
  87.                 String activityName = reInfo.activityInfo.name;     // 获得应用程序启动Activity的name  
  88.                 String pkgName = reInfo.activityInfo.packageName;   // 获得应用程序的包名  
  89.                 String appLabel = (String)reInfo.loadLabel(pm);     // 获得应用程序的Label  
  90.                 Drawable icon = reInfo.loadIcon(pm);                // 获得应用程序的图标  
  91.                   
  92.                 // 为应用程序的启动Activity准备Intent  
  93.                 Intent launchIntent = new Intent();  
  94.                 launchIntent.setComponent(new ComponentName(pkgName, activityName));  
  95.                   
  96.                 // 创建一个 AppInfo 对象  
  97.                 AppInfo appInfo = new AppInfo(this);  
  98.                 appInfo.setAppLabel(appLabel);  
  99.                 appInfo.setAppIcon(icon);  
  100.                 appInfo.setPkgName(pkgName);  
  101.                 appInfo.setIntent(launchIntent);  
  102.                   
  103.                 mListAppInfos.add(appInfo);  
  104.                   
  105.                 Log.i(LOG_TAG, "ActivityName:"+activityName+ "pkgName:"+pkgName);  
  106.             }     
  107.         }  
  108.     }  
  109.   
  110.     @Override  
  111.     public void onItemClick(AdapterView<?> adapter, View view, int arg2, long arg3) {  
  112.         // TODO Auto-generated method stub  
  113.         Intent intent = mListAppInfos.get(arg2).getIntent();  
  114.         Log.d(LOG_TAG, "intent:"+intent.toString());  
  115.         startActivity(intent);  
  116.     }  
  117.   
  118. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值