当前位置:   article > 正文

Android常用适配器分析(如何制作简易Launcher)_android 10 做成launcher

android 10 做成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:

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

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

  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集合。如:

  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:

    

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

 

2)SimpleAdapter

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

Demo:

     simple_list.xml

  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. <TextView
  7. android:id="@+id/textView"
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:layout_margin="20dp"
  11. android:textIsSelectable="true" >
  12. </TextView>
  13. <ImageView
  14. android:id="@+id/img"
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:layout_margin="20sp" >
  18. </ImageView>
  19. </LinearLayout>

     MainActivity.java

 

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

 

3)CursorAdapter

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

Demo:

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

 

4)BaseAdapter

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

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

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

  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. public AppInfo(Context context) {
  8. this.context = context;
  9. }
  10. public String getAppLabel() {
  11. return appLabel;
  12. }
  13. public void setAppLabel(String appName) {
  14. this.appLabel = appName;
  15. }
  16. public Drawable getAppIcon() {
  17. return appIcon;
  18. }
  19. public void setAppIcon(Drawable appIcon) {
  20. this.appIcon = appIcon;
  21. }
  22. public Intent getIntent() {
  23. return intent;
  24. }
  25. public void setIntent(Intent intent) {
  26. this.intent = intent;
  27. }
  28. public String getPkgName() {
  29. return pkgName;
  30. }
  31. public void setPkgName(String pkgName) {
  32. this.pkgName = pkgName;
  33. }
  34. }

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

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

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

  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. <ImageView android:id="@+id/imgApp"
  7. android:layout_width="wrap_content"
  8. android:layout_height="fill_parent">
  9. </ImageView>
  10. <RelativeLayout
  11. android:layout_width="fill_parent"
  12. android:layout_height="40dp"
  13. android:layout_marginLeft="10dp">
  14. <TextView android:id="@+id/tvLabel"
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:text="AppLabel:">
  18. </TextView>
  19. <TextView android:id="@+id/tvAppLabel"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:layout_marginLeft="3dp"
  23. android:text="Label"
  24. android:layout_toRightOf="@id/tvLabel"
  25. android:textColor="#ffD700">
  26. </TextView>
  27. <TextView android:id="@+id/tvName"
  28. android:layout_width="wrap_content"
  29. android:layout_height="wrap_content"
  30. android:layout_below="@id/tvLabel"
  31. android:text="包名">
  32. </TextView>
  33. <TextView android:id="@+id/tvPkgName"
  34. android:layout_width="wrap_content"
  35. android:layout_height="wrap_content"
  36. android:layout_below="@id/tvAppLabel"
  37. android:layout_alignLeft="@id/tvAppLabel"
  38. android:textColor="#ffD700">
  39. </TextView>
  40. </RelativeLayout>"
  41. </LinearLayout>

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

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

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/377041
推荐阅读
相关标签
  

闽ICP备14008679号