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:

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

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

<TextView xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@android:id/text1"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:textAppearance="?android:attr/textAppearanceListItemSmall"    android:gravity="center_vertical"    android:paddingStart="?android:attr/listPreferredItemPaddingStart"    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"    android:minHeight="?android:attr/listPreferredItemHeightSmall"/>

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

private List<String> getData() {List<String> data = new ArratList<String>();data.add("one");data.add("two");data.add("three");data.add("four");data.add("three");return data;}

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

Demo2:

public class MainActivity extends ListActivity {private ListView listView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item1, getData());setListAdapter(adapter);}private List<String> getData() {List<String> data = new ArrayList<String>();data.add("one");data.add("two");data.add("three");return data;}}

2)SimpleAdapter

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

Demo:

simple_list.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:orientation="horizontal" >    <TextView        android:id="@+id/textView"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_margin="20dp"        android:textIsSelectable="true" >    </TextView>    <ImageView        android:id="@+id/img"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_margin="20sp" >    </ImageView></LinearLayout>

MainActivity.java

public class MainActivity extends ListActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);String [] strings = new String[] {"title", "img"};int[] ids = new int[] {R.id.textView, R.id.img};SimpleAdapter adapter = new SimpleAdapter(this, getData(), R.layout.simple_list, strings, ids);setListAdapter(adapter);}private List<Map<String, Object>> getData() {List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();Map<String, Object> map = new HashMap<String, Object>();map.put("title", "Hello");map.put("img", R.drawable.iag);list.add(map);map = new HashMap<String, Object>();map.put("title", "world");map.put("img", R.drawable.ic_launcher);list.add(map);return list;}}

3)CursorAdapter

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

Demo:

@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);Cursor  cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null);startManagingCursor(cursor);ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.simple_list, cursor, new String[] {People.NAME}, new int[] {R.id.textView});setListAdapter(adapter);}

4)BaseAdapter

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

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

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

public class AppInfo {private String appLabel;// 应用程序标签private Drawable appIcon;// 应用程序 的图像private Intent intent; private String pkgName;// 应用程序所对应包名private Context context;public AppInfo(Context context) {this.context = context;}public String getAppLabel() {return appLabel;}public void setAppLabel(String appName) {this.appLabel = appName;}public Drawable getAppIcon() {return appIcon;}public void setAppIcon(Drawable appIcon) {this.appIcon = appIcon;}public Intent getIntent() {return intent;}public void setIntent(Intent intent) {this.intent = intent;}public String getPkgName() {return pkgName;}public void setPkgName(String pkgName) {this.pkgName = pkgName;}}

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

public class ApplicationInfoAdapter extends BaseAdapter {private static final String TAG = "ApplicationInfoAdapter";private List<AppInfo> mListAppInfo = null;LayoutInflater infater = null;public ApplicationInfoAdapter(Context context, List<AppInfo> apps) {// TODO Auto-generated constructor stubinfater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);mListAppInfo = apps;}@Overridepublic int getCount() {// TODO Auto-generated method stubLog.i(TAG, "size="+mListAppInfo.size());return mListAppInfo.size();}@Overridepublic Object getItem(int arg0) {// TODO Auto-generated method stubreturn mListAppInfo.get(arg0);}@Overridepublic long getItemId(int arg0) {// TODO Auto-generated method stubreturn 0;}@Overridepublic View getView(int position, View convertView, ViewGroup viewGroup) {// TODO Auto-generated method stubLog.i(TAG, "getView at" + position);View view = null;ViewHolder holder = null;if(convertView == null || convertView.getTag()==null) {view = infater.inflate(R.layout.app_list, null);holder = new ViewHolder(view);view.setTag(holder);} else {view = convertView;holder = (ViewHolder)convertView.getTag();}AppInfo appInfo = (AppInfo)getItem(position);holder.appIcon.setImageDrawable(appInfo.getAppIcon());holder.tvAppLabel.setText(appInfo.getAppLabel());holder.tvPktName.setText(appInfo.getPkgName());return view;}class ViewHolder {ImageView appIcon;TextView tvAppLabel;TextView tvPktName;public ViewHolder(View view) {this.appIcon = (ImageView)view.findViewById(R.id.imgApp);this.tvAppLabel = (TextView)view.findViewById(R.id.tvAppLabel);this.tvPktName = (TextView)view.findViewById(R.id.tvPkgName);}}}

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

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="50dp"    android:orientation="horizontal" >        <ImageView android:id="@+id/imgApp"        android:layout_width="wrap_content"        android:layout_height="fill_parent">    </ImageView>        <RelativeLayout         android:layout_width="fill_parent"        android:layout_height="40dp"        android:layout_marginLeft="10dp">                <TextView android:id="@+id/tvLabel"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="AppLabel:">        </TextView>                <TextView android:id="@+id/tvAppLabel"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="3dp"            android:text="Label"            android:layout_toRightOf="@id/tvLabel"            android:textColor="#ffD700">        </TextView>                <TextView android:id="@+id/tvName"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_below="@id/tvLabel"            android:text="包名">        </TextView>        <TextView android:id="@+id/tvPkgName"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_below="@id/tvAppLabel"            android:layout_alignLeft="@id/tvAppLabel"            android:textColor="#ffD700">        </TextView>    </RelativeLayout>"</LinearLayout>

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

public class MainActivity extends Activity implements OnItemClickListener {private static final String LOG_TAG = "MainActivity";private static final int MSG_SUCCESS = 0;private ListView listView = null;private List<AppInfo> mListAppInfos = null;Handler mHandler = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);listView = (ListView) this.findViewById(R.id.listView);mListAppInfos = new ArrayList<AppInfo>();mHandler = new Handler() {public void handleMessage(android.os.Message msg) {switch (msg.what) {case MSG_SUCCESS:ApplicationInfoAdapter applicationInfoAdapter = new ApplicationInfoAdapter(MainActivity.this, mListAppInfos); listView.setAdapter(applicationInfoAdapter);listView.setOnItemClickListener(MainActivity.this);break;default:break;}};};new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubqueryAppInfo(); // 查询所有应用程序信息mHandler.obtainMessage(MSG_SUCCESS).sendToTarget();}}).start();}public void queryAppInfo() {PackageManager pm = this.getPackageManager();/* List<ApplicationInfo> listApplications = pm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES); Collections.sort(listApplications, new ApplicationInfo.DisplayNameCoamparator(pm)); for(ApplicationInfo app : listApplications) { if((app.flags & ApplicationInfo.FLAG_SYSTEM) > 0) {// 系统程序 } else if( (app.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {// 第三方程序  } else if((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {// 系统程序被用户更新了  } else if((app.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {// 安装在SD卡程序  } }*/Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);// 查询获得所有ResolveInfo对象List<ResolveInfo> resolveInfos = pm.queryIntentActivities(mainIntent, PackageManager.MATCH_DEFAULT_ONLY);for(ResolveInfo reInfo : resolveInfos) {Log.e(LOG_TAG, "name:"+reInfo.activityInfo.name + "pkg:"+reInfo.activityInfo.packageName);}// 根据name排序Collections.sort(resolveInfos, new ResolveInfo.DisplayNameComparator(pm));for(ResolveInfo reInfo : resolveInfos) {Log.e(LOG_TAG, "name:"+reInfo.activityInfo.name + "pkg:"+reInfo.activityInfo.packageName);}if(mListAppInfos != null) {mListAppInfos.clear();for(ResolveInfo reInfo : resolveInfos) {String activityName = reInfo.activityInfo.name;// 获得应用程序启动Activity的nameString pkgName = reInfo.activityInfo.packageName;// 获得应用程序的包名String appLabel = (String)reInfo.loadLabel(pm);// 获得应用程序的LabelDrawable icon = reInfo.loadIcon(pm);// 获得应用程序的图标// 为应用程序的启动Activity准备IntentIntent launchIntent = new Intent();launchIntent.setComponent(new ComponentName(pkgName, activityName));// 创建一个 AppInfo 对象AppInfo appInfo = new AppInfo(this);appInfo.setAppLabel(appLabel);appInfo.setAppIcon(icon);appInfo.setPkgName(pkgName);appInfo.setIntent(launchIntent);mListAppInfos.add(appInfo);Log.i(LOG_TAG, "ActivityName:"+activityName+ "pkgName:"+pkgName);}}}@Overridepublic void onItemClick(AdapterView<?> adapter, View view, int arg2, long arg3) {// TODO Auto-generated method stubIntent intent = mListAppInfos.get(arg2).getIntent();Log.d(LOG_TAG, "intent:"+intent.toString());startActivity(intent);}}

更多相关文章

  1. android屏幕适配建议 (二)
  2. Android(安卓)- 布局(layout) 详解
  3. 实现android JNI 直接调用android驱动程序
  4. android学习日记13--数据存储之ContentProvide
  5. Android/Ophone应用程序数字签名
  6. android学习——GridView实现主界面布局
  7. Android(安卓)recycleview实现左右切换时的条目滑动效果,条目是固
  8. android中跨进程通讯的4种方式
  9. Android-沉浸式布局的玩法

随机推荐

  1. 看动画轻松理解时间复杂度(一)
  2. 从简单的线性数据结构开始:穿针引线的链表
  3. Excelize 2.3.2 发布, Go 语言 Excel 文档
  4. 图解LeetCode第 3 号问题:无重复字符的最
  5. 在数据结构中穿针引线:链表实现栈和队列
  6. 摄像机通道号对接
  7. 看动画轻松理解时间复杂度(二)
  8. AliRTC QoS 屏幕共享弱网优化之若干编码
  9. Android(安卓)studio 使用心得(一)---and
  10. 图解LeetCode第 26 号问题:删除排序数组中