Android基础教程:促进AlertDialog通用化的另一种实现方式
Android基础教程:促进AlertDialog通用化的另一种实现方式
在Android的技术文档中,关于AlertDialog的创建,有如下的代码。http://developer.android.com/guide/topics/ui/dialogs.html- final CharSequence[] items = {"Red", "Green", "Blue"};
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle("Pick a color");
- builder.setItems(items, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int item) {
- Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
- }
- });
- AlertDialog alert = builder.create();
参照这段代码可以很简单的构建自己的包含列表的对话框。但是有一点小小的遗憾,就是在setItems中设定的DialogInterface.OnClickListener的onClick中取得选中项目的时候,利用了onClick的参数和尾部的items的信息。作为例子当然没有问题,但是如果想将这部分代码通用的时候就会有困难,解决办法应该有很多,这里向大家推荐以下的方法。
先上代码
- AlertDialog createAlertDialog(final int dialog_id, CharSequence[] items, OnItemClickListener listener){
- AlertDialog.Builder builder = new AlertDialog.Builder(activity);
- builder.setTitle(dialog_id);
- builder.setItems(items, null);
- builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
- @Override
- public void onCancel(DialogInterface dialog) {
- activity.removeDialog(dialog_id);
- }
- });
- AlertDialog dialog = builder.create();
- dialog.getListView().setOnItemClickListener(listener);
- return dialog;
- }
主要的变化就是没有直接使用AlertDialog.Buider的setItems中Listener,而是取得ListView后指定OnItemClickListener。它的声明如下:
void onItemClick(AdapterView<?> parent, View view, int position, long id)
参数中有ListView的信息,因此可以相对简单的中自身,而不是外部取得信息。
评论暂时关闭