ApiDemo学习之路(1)---API demo的入口

来源:互联网 发布:淘宝砍价师怎么砍价的 编辑:程序博客网 时间:2024/04/30 04:30

其实很多android的答案都是在APIdemo中的,所以彻底研究APIdemo源码才是提升android功力最好的方法,下面我会将我的APIdemo学习同大家分享.

既然是研究源码,就要有个入口,而APIdemo的入口文件就是ApiDemos.java,这个很容易通过AndroidManefest.xml文件可知.

<activity android:name="ApiDemos">

            <intent-filter>

                <actionandroid:name="android.intent.action.MAIN"/>

                <categoryandroid:name="android.intent.category.DEFAULT"/>

                <category android:name="android.intent.category.LAUNCHER"/>

            </intent-filter>

        </activity>

android:name="android.intent.category.LAUNCHER这个Category就说明了会显示在Launcher中,所以此处就是当在launcher中点击API demo的icon所调用的第一个Activity.

ApiDemos是一个ListActivity,因此我们所看到必然是一个列表形式的Activity,如图中所示,那么这个列表是怎么生成的呢?既然是list那必然就会有对应的adapter,从代码处可看到


setListAdapter(new SimpleAdapter(this, getData(path),

                android.R.layout.simple_list_item_1,new String[] { "title" },

               new int[]{ android.R.id.text1}));

其中的关键就是getData(path)这个的返回,因为数据都是在其中生成的.

这个方法也很简单,通过packagemanager 去query所有Activity的category为CATEGORY_SAMPLE_CODE的activity,同样去看AndroidManefest.xml文件,可知道哪些Activity的intentfilter 是设置为CATEGORY_SAMPLE_CODE.

这里有一个地方要注意就是,实际上query出来的是很长的一个列表,但是这里做了分类,会将同一个类型的放到一起,实现的方式是通过判断label来实现的,这里以第一项的Animation为例:

Animation实际上是一类label含有Animation/集合,这里就以Animation 中的第一项BouncingBalls为例,其label是Animation/Bouncing Balls,那么在执行到下面之后会是:

String[] labelPath = label.split("/");后就会分成2个Animation和BouncingBalls

 

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

这里prefixPath是null,因此nextLable此处就是Animation,因为prefixPath为null,所以会执行到下面

if (entries.get(nextLabel) ==null) {

addItem(myData, nextLabel,browseIntent(prefix.equals("") ?nextLabel : prefix + "/" + nextLabel));

entries.put(nextLabel, true);

                   }

而在这里会设置一个”path”参数在browseIntent()中,

protected IntentbrowseIntent(String path) {

        Intent result = new Intent();

        result.setClass(this, ApiDemos.class);

        result.putExtra("com.example.android.apis.Path", path);

        return result;

    }

这样一级菜对应的intenttarget class就是ApiDemos.class,其次设置参数,这里也就是Animation,所以当点击Animation时候,实际上运行的方式是再次LaunchApiDemos,而prefixPath就是Animation,

所以此时StringnextLabel = prefixPath == null? labelPath[0] : labelPath[prefixPath.length];这里的nextLabel就会是Bouncing Balls

那么if ((prefixPath !=null ? prefixPath.length : 0) ==labelPath.length - 1) {

addItem(myData, nextLabel,activityIntent(

                            info.activityInfo.applicationInfo.packageName,

                            info.activityInfo.name));

               }

因此会对应BouncingBalls添加对应的intent,从而当点击的时候,会launch Bouncing Balls对应的Activity.

实现点击的地方则是在

protected voidonListItemClick(ListView l, View v, int position,long id) {

Map<String, Object> map =(Map<String, Object>)l.getItemAtPosition(position);

 

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

        startActivity(intent);

    }

通过Map的方式找到对应位置的intent.

原创粉丝点击