android2.3 api demo 学习系列(1)--apidemo主列表的实现

android最有价值的参考资料莫过于sdk提供的apidemos,现在我们就开始一点一点的学习,本人水平有限,文章中出现错误请您指正。

sdk中得apidemos接近200个,设计到android的各个方面,首先先学习下android的开发人员如何将这200多个demo分类的。

1、首先在AndroidManifest.xml注册activity时附件以下intent-filter 例如

 

<activity android:name=".app.Animation" android:label="@string/activity_animation">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.angie.apidemos.SAMPLE_CODE" />
            </intent-filter>
        </activity>

  2、在values/Strings.xml 声明该activity的label值 (这样声明是为了下面的list分类)

 

 

<string name="activity_animation">App/Activity/Animation</string>

  3、最后在自己的activity里面处理list

 

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //获取传递进来的附加信息
        Intent intent = getIntent();
        String path = intent.getStringExtra("com.angie.apidemos.Path");
        
        if (path == null) {
            path = "";
        }
        //create list
        setListAdapter(new SimpleAdapter(this, getData(path),
                R.layout.mainlist, new String[] { "image", "title" },
                new int[] { R.id.rowImage, R.id.rowTitle }));
        getListView().setTextFilterEnabled(true);
    }
    protected List getData(String prefix) {
        List<Map> myData = new ArrayList<Map>();

        //获取符合条件的activity  (包含其他应用程序符合条件的activity) 
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(MyApplication.CATEGORY_SAMPLE_CODE);

        PackageManager pm = getPackageManager();
        List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);

        if (null == list)
            return myData;

        String[] prefixPath;
        
        if (prefix.equals("")) {
            prefixPath = null;
        } else {
            prefixPath = prefix.split("/");
        }
        
        int len = list.size();
        
        Map<String, Boolean> entries = new HashMap<String, Boolean>();

        for (int i = 0; i < len; i++) {
            ResolveInfo info = list.get(i);
            CharSequence labelSeq = info.loadLabel(pm); 
            String label = labelSeq != null
                    ? labelSeq.toString()
                    : info.activityInfo.name;

            if (prefix.length() == 0 || label.startsWith(prefix)) {
                
                String[] labelPath = label.split("/");

                String nextLabel = prefixPath == null ? labelPath[0] : labelPath[prefixPath.length];

                if ((prefixPath != null ? prefixPath.length : 0) == labelPath.length - 1) {
                    addItem(myData, nextLabel, activityIntent(
                            info.activityInfo.applicationInfo.packageName,
                            info.activityInfo.name),
                            R.drawable.launcher);
                } else {
                    if (entries.get(nextLabel) == null) {
                        addItem(myData, nextLabel, browseIntent(prefix.equals("") ? nextLabel : prefix + "/" + nextLabel),R.drawable.list);
                        entries.put(nextLabel, true);
                    }
                }
            }
        }

        Collections.sort(myData, sDisplayNameComparator);
        
        return myData;
    }

    private final static Comparator<Map> sDisplayNameComparator = new Comparator<Map>() {
        private final Collator   collator = Collator.getInstance();

        public int compare(Map map1, Map map2) {
            return collator.compare(map1.get("title"), map2.get("title"));
        }
    };

    protected Intent activityIntent(String pkg, String componentName) {
        Intent result = new Intent();
        result.setClassName(pkg, componentName);
        return result;
    }
    
    protected Intent browseIntent(String path) {
        Intent result = new Intent();
        result.setClass(this, ApiDemosStudyActivity.class);
        result.putExtra("com.angie.apidemos.Path", path);
        return result;
    }

    protected void addItem(List<Map> data, String name, Intent intent, int image) {
        Map<String, Object> temp = new HashMap<String, Object>();
        temp.put("image", image);
        temp.put("title", name);
        temp.put("intent", intent);
        data.add(temp);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Map map = (Map) l.getItemAtPosition(position);

        Intent intent = (Intent) map.get("intent");
        startActivity(intent);
    }

 4、上面的代码没有特别难理解的地方,故不再一一注释。其中用到的mainlist定义如下

 

<?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:gravity="center_vertical"
	android:orientation="horizontal">
	<ImageView
		android:id="@+id/rowImage"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:gravity="center_vertical"
		android:paddingLeft="6dip"
		android:src="@drawable/list" />
	<TextView
		android:id="@+id/rowTitle"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:textAppearance="?android:attr/textAppearanceLarge"
		android:gravity="center_vertical"
		android:paddingLeft="6dip"
		android:minHeight="?android:attr/listPreferredItemHeight"/>	
</LinearLayout>
 

 

 注:代码中用到的drawable资源请自行导入,不再赘述。

其中用到的MyApplication类主要是想定义一个CATEGORY_SAMPLE_CODE,你也可以放弃这种方式 直接使用intent内部定义的CATEGORY。代码示例如下

 

public class MyApplication extends Application {

	public static final String CATEGORY_SAMPLE_CODE = "com.angie.apidemos.SAMPLE_CODE";
	/* (non-Javadoc)
	 * @see android.app.Application#onCreate()
	 */
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	}

}

效果图:

android2.3 api demo 学习系列(1)--apidemo主列表的实现

 

你可能感兴趣的:(android,demo,ApiDemos)