Android基础教程:促进AlertDialog通用化的另一种实现方式


在Android的技术文档中,关于AlertDialog的创建,有如下的代码。http://developer.android.com/guide/topics/ui/dialogs.html
  1. final CharSequence[] items = {"Red""Green""Blue"};  
  2.   
  3. AlertDialog.Builder builder = new AlertDialog.Builder(this);  
  4. builder.setTitle("Pick a color");  
  5. builder.setItems(items, new DialogInterface.OnClickListener() {  
  6.     public void onClick(DialogInterface dialog, int item) {  
  7.         Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();  
  8.     }  
  9. });  
  10. AlertDialog alert = builder.create();  

参照这段代码可以很简单的构建自己的包含列表的对话框。但是有一点小小的遗憾,就是在setItems中设定的DialogInterface.OnClickListener的onClick中取得选中项目的时候,利用了onClick的参数和尾部的items的信息。作为例子当然没有问题,但是如果想将这部分代码通用的时候就会有困难,解决办法应该有很多,这里向大家推荐以下的方法。

先上代码

  1. AlertDialog createAlertDialog(final int dialog_id, CharSequence[] items, OnItemClickListener listener){  
  2.         AlertDialog.Builder builder = new AlertDialog.Builder(activity);  
  3.         builder.setTitle(dialog_id);  
  4.         builder.setItems(items, null);  
  5.         builder.setOnCancelListener(new DialogInterface.OnCancelListener() {  
  6.         @Override  
  7.         public void onCancel(DialogInterface dialog) {  
  8.                 activity.removeDialog(dialog_id);  
  9.         }  
  10.     });  
  11.     AlertDialog dialog =  builder.create();  
  12.     dialog.getListView().setOnItemClickListener(listener);  
  13.     return dialog;  
  14. }  

主要的变化就是没有直接使用AlertDialog.Buider的setItems中Listener,而是取得ListView后指定OnItemClickListener。它的声明如下:

void onItemClick(AdapterView<?> parent, View view, int position, long id)

参数中有ListView的信息,因此可以相对简单的中自身,而不是外部取得信息。

相关内容