您的位置:首页 > 移动开发 > Android开发

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

2014-08-07 18:07 447 查看
http://blog.csdn.net/column/details/llping2010.html

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
plaincopyprint?

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,其实际内容如下:

[html] view
plaincopyprint?

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

[html] view
plaincopyprint?

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:

[html] view
plaincopyprint?

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

[html] view
plaincopyprint?

<?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

[html] view
plaincopyprint?

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:

[html] view
plaincopyprint?

@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:

[html] view
plaincopyprint?

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()等函数。

[html] view
plaincopyprint?

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用来显示每一个应用程序的信息

[html] view
plaincopyprint?

<?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上。

[html] view
plaincopyprint?

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);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: