Android Samples-Notepad分析之一
该Notepad应用包含三个Activity
1.供显示当前应用所有的日记,也就是一个日记列表,继承自ListActivity,应用启动的主页面
该Activity包含以下内容:
上下文菜单:在某一行上长按弹出相应菜单,菜单包含一个标题与删除选项,主要有以下几个方法里实现
onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo),onContextItemSelected(MenuItem item)
在onCreate()里绑定一个上下文菜单,绑定方法如下:
getListView().setOnCreateContextMenuListener(this);
菜单:当前ListActivity没有项被选中时,只有一个添加菜单,点击跳转到内容编辑页面
startActivity(new Intent(Intent.ACTION_INSERT, getIntent().getData()));
采取action + uri 方式进行跳转
如果当前ListActivity有选中项,会另外再动态添加二个菜单(编辑当前内容 、 编辑当前标题)+ 添加菜单
此处采用动态添加技术,具体代码如下:
Intent[] specifics = new Intent[1];
specifics[0] = new Intent(Intent.ACTION_EDIT, uri);
MenuItem[] items = new MenuItem[1];
//采取action + data
Intent intent = new Intent(null,uri);
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
//采取 category + data
menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0,
new ComponentName(this, NotepadListActivity.class), specifics, intent, 0, items);
上述代码采取二种适配方式,在onPrepareOptionsMenu(Menu menu)里进行相关处理,如果manifest.xml中有匹配这二种方式,就会生成相应菜单,名称取自intent-filter 里的label,没有匹配成功,则不生成相应的菜单
2.单个日记的内容编辑页面,继承自Activity
当前Activity中自定义了一个编辑控件,继承自 EditText
在onCreate()里会判断当前action,编辑与插入处理方式不同,当action为插入时,会事先向ContentProvider做一次插入操作,去创建相应数据,并返回对应的Uri,数据的保存都在onPause里处理,根据相应的Uri作Update操作
该Activity里也有动态菜单的处理,当action为编辑里,会动态添加一个标题编辑菜单
3.单个日记的标题编辑页面,继承自Activty
编辑当前标题,该Activity的主题为Dialog,数据的保存也是在onPause里
这个事例是对针对ContentProvider的使用,给出的一个简单demo
ContentProvider是一个抽象类,继承它必须实现它所有抽象方法,包含如下:
The primary methods that need to be implemented are:
-
onCreate()
which is called to initialize the provider -
query(Uri, String[], String, String[], String)
which returns data to the caller -
insert(Uri, ContentValues)
which inserts new data into the content provider -
update(Uri, ContentValues, String, String[])
which updates existing data in the content provider -
delete(Uri, String, String[])
which deletes data from the content provider -
getType(Uri)
which returns the MIME type of data in the content provider
针对动态菜单的添加,data数据与manifest.xml匹配时,系统会通过getType(Uri)得到相应的MIME数据,这个数据需要开发者自己定义,格式如下:vnd.android.cursor.dir/? vnd.android.cursor.item/?
简单写了点本人对这个事例的理解,不可能面面居到,有不理解的地方,我们可以交流交流!谢谢!