**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;
@Override
protected 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;
@Override
protected 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 {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.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:
~~~
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.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 stub
infater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mListAppInfo = apps;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
Log.i(TAG, "size="+mListAppInfo.size());
return mListAppInfo.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return mListAppInfo.get(arg0);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
// TODO Auto-generated method stub
Log.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;
@Override
protected 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() {
@Override
public void run() {
// TODO Auto-generated method stub
queryAppInfo(); // 查詢所有應用程序信息
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的name
String pkgName = reInfo.activityInfo.packageName; // 獲得應用程序的包名
String appLabel = (String)reInfo.loadLabel(pm); // 獲得應用程序的Label
Drawable icon = reInfo.loadIcon(pm); // 獲得應用程序的圖標
// 為應用程序的啟動Activity準備Intent
Intent 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);
}
}
}
@Override
public void onItemClick(AdapterView<?> adapter, View view, int arg2, long arg3) {
// TODO Auto-generated method stub
Intent intent = mListAppInfos.get(arg2).getIntent();
Log.d(LOG_TAG, "intent:"+intent.toString());
startActivity(intent);
}
}
~~~
- 前言
- Android開發之serviceManager分析
- Android啟動之init.c文件main函數分析
- Android開發之ProcessState和IPCThreadState類分析
- Android開發之MediaPlayerService服務詳解(一)
- Android系統五大布局詳解Layout
- Android四大組件之Content Provider
- Android四大組件之Service
- Android四大組件之BroadcastReceiver
- Android系統中的消息處理Looper、Handler、Message
- Android EditText/TextView使用SpannableString顯示復合文本
- Android關鍵資源詳解
- Android常用適配器分析(如何制作簡易Launcher)
- Android常用列表控件