Android Sample NotePad (一)

主程序(activity):
Notelist, 继承ListActivity

在onCreate方法中:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);

        // If no data was given in the intent (because we were started
        // as a MAIN activity), then use our default content provider.
        Intent intent = getIntent();
        if (intent.getData() == null) {
            intent.setData(Notes.CONTENT_URI);
        }

        // Inform the list we provide context menus for items
        getListView().setOnCreateContextMenuListener(this);
        
        // Perform a managed query. The Activity will handle closing and requerying the cursor
        // when needed.
        Cursor cursor = managedQuery(getIntent().getData(), PROJECTION, null, null,
                Notes.DEFAULT_SORT_ORDER);

        // Used to map notes entries from the database to views
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.noteslist_item, cursor,
                new String[] {Notes.TITLE }, new int[] { android.R.id.text1 });
        setListAdapter(adapter);
    }

intent =getIntent() 是一个隐式的intent, 因为是主Acticity, 所以没有其他的Activity直接pass intent 给它。 只有在ActivityManifest中定义了Intent-filter的Activity才可以

接受隐式的Intent。

Notes.CONTENT_URI is a constant defined in the Notepad.java 类中。

getListView() will return us the local ListView object for the Activity。

Cursor 其实是指向数据库的指针,manageQuery方法是从content provider 里面返回一个指针,第一个参数是content provider 的Uri, 第二个参数是数据库的一个要看的域,比如联络信息中的人名,PROJECTION 定义好的字符串,指明要访问的columns. row 参数为空说明选择所有行,最后一个是排序的方法。

因为Notelist 是继承了ListActivity, 所以它默认绑定了一个全屏的Listview, 所以一般必须注释掉setContentView。

如果用自定义,customered 的布局文件, 需要注意的是在xml文件中,这个Listview 的id必须设置为@android.id/list, 也即是android系统设置的list id, 这个id, 以及

android.r.id.text1, 都是定义在android.r 类中的常数,在整个android系统中都是唯一的。(也可以理解为Listactivity默认带的Listview就是用的这个id).  也因为这个,所以按理说一个程序里面只能有一个listactivity。 如果需要两个Listview 怎么办呢?简单的方法是在另一个activity中包含listview, 但是该activity不要继承listactivity.

一个Listactivity需要listview, 适配器(adapter) 和数据。 SimpleCursorAdapter 是android提供的一个适配器, 几种适配器的区别是数据源不同而已
1. String[]: ArrayAdapter  最简单的字符串数据
2. List<Map<String,?>>: SimpleAdapter Hashmap 数据源,可以包括图片,button。
3. 数据库Cursor: SimpleCursorAdapter

posted on 2010-12-15 23:07  风水流转  阅读(879)  评论(0)    收藏  举报

导航