2011年12月01日09:34 来源: 博客园作者:诚实小郎君 编辑: 景保玉 我要评论(0)

  【IT168技术】Dialog是android开发过程中最常用到的组件之一,它包括以下几种类型:

  警告对话框:Alertialog

  进度对话框:ProgressDialog

  日期选择对话框:DatePickerDialog

  时间选择对话框:TimePickerDialog

  自定义对话框:从Dialog继承

  Dialog的创建方式有两种:

  一是直接new一个Dialog对象,然后调用Dialog对象的show和dismiss方法来控制对话框的显示和隐藏。

  二是在Activity的onCreateDialog(int id)方法中创建Dialog对象并返回,然后调用Activty的showDialog(int id)和dismissDialog(int id)来显示和隐藏对话框。

  区别在于通过第二种方式创建的对话框会继承Activity的属性,比如获得Activity的menu事件等。

  使用AlertDialog可以创建普通对话框、带列表的对话框以及带单选按钮和多选按钮的对话框。

  普通对话框

  效果如下:

  

  代码:


     // 创建builder
                AlertDialog.Builder builder = new AlertDialog.Builder(DialogSampleActivity.this);
                builder.setTitle( " 普通对话框 " )     // 标题
                    .setIcon(R.drawable.ic_launcher)     // icon
                    .setCancelable( false )     // 不响应back按钮
                    .setMessage( " 这是一个普通对话框 " )     // 对话框显示内容
                   // 设置按钮
                    .setPositiveButton( " 确定 " , new DialogInterface.OnClickListener() {
                        @Override
                         public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(DialogSampleActivity.this, " 点击了确定按钮 " , Toast.LENGTH_SHORT).show();
                        }
                    })
                    .setNeutralButton( " 中立 " , new DialogInterface.OnClickListener() {                        
                        @Override
                         public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(DialogSampleActivity.this, " 点击了中立按钮 " , Toast.LENGTH_SHORT).show();
                        }
                    })
                    .setNegativeButton( " 取消 " , new DialogInterface.OnClickListener() {                    
                        @Override
                         public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(DialogSampleActivity.this, " 点击了取消按钮 " , Toast.LENGTH_SHORT).show();
                        }
                    });
                 // 创建Dialog对象
                AlertDialog dlg = builder.create();
                return dlg;

  带列表的对话框

  效果图:

  代码:

 final CharSequence[] items = { " Item1 " , " Item2 " , " Item3 " };
             // 创建builder
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    DialogSampleActivity.this);
            builder.setTitle( " 列表对话框 " ) // 标题
                    .setIcon(R.drawable.ic_launcher) // icon
                    .setCancelable( false ) // 不响应back按钮
                    .setItems(items, new DialogInterface.OnClickListener() {
                        @Override
                         public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(DialogSampleActivity.this,
                                     " 选择了 " + items[which], Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });
             // 创建Dialog对象
            AlertDialog dlg = builder.create();
            return dlg;

  带单选按钮的列表对话框

  只需将setItems替换为:

.setSingleChoiceItems(items, - 1 , new DialogInterface.OnClickListener() {
                        @Override
                         public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(DialogSampleActivity.this,
                                     " 选择了 " + items[which], Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });

  这里多了一个参数-1,代表默认选中第几项,-1表示默认不选中

  带复选框的列表对话框

  只需将setItems替换为:


.setMultiChoiceItems(items, checked, new DialogInterface.OnMultiChoiceClickListener() {        
                        @Override
                         public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                            Toast.makeText(DialogSampleActivity.this,
                                     " 选择了 " + items[which], Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });

  参数checked伟boolean数组,表示默认哪些复选框是被选中的。

  另外,如果你想要获取list中哪些项是被选中的,你需要:

// 获得ListView
ListView list = dlg.getListView();
// 判断第i项是否被选中,为真表示被选中,为假表示没有选中
list.getCheckedItemPositions().get(i)

  日期选择对话框

  效果图:

  代码:

Calendar calendar = Calendar.getInstance();
            DatePickerDialog.OnDateSetListener dateListener =   
                 new DatePickerDialog.OnDateSetListener() {  
                    @Override  
                     public void onDateSet(DatePicker datePicker,  
                             int year , int month , int dayOfMonth) {  
                        Toast.makeText(DialogSampleActivity.this,
                                 year + " 年 " + ( month + 1 ) + " 月 " + dayOfMonth + " 日 " , Toast.LENGTH_SHORT)
                                .show();  
                    }
                };  
            DatePickerDialog dlg = new DatePickerDialog(
                    DialogSampleActivity.this,
                    dateListener,
                    calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH));
            return dlg;

  时间选择对话框

  效果图:

  代码:

 Calendar calendar = Calendar.getInstance();
            TimePickerDialog.OnTimeSetListener timeListener =   
                 new TimePickerDialog.OnTimeSetListener() {

@Override
                     public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute ) {
                        Toast.makeText(DialogSampleActivity.this,
                                hourOfDay + " : " + minute , Toast.LENGTH_SHORT).show();  
                    }  
                  
                };  
            TimePickerDialog dlg = new TimePickerDialog(
                    DialogSampleActivity.this,
                    timeListener,
                    calendar.get(Calendar.HOUR_OF_DAY),
                    calendar.get(Calendar.MINUTE),
                     true );
            return dlg;

  自定义对话框

  效果图:

  步骤:

  1、创建对话框的布局文件

< ?xml version = " 1.0 " encoding = " utf-8 " ? >
< RelativeLayout
    xmlns:android = " http://schemas.android.com/apk/res/android "
      android:layout_width = " wrap_content "
      android:layout_height = " wrap_content " >
       < ! -- 标题栏 -->
       < LinearLayout
          android:id = " @+id/dlg_priority_titlebar "
          android:orientation = " horizontal "
          android:layout_width = " fill_parent "
          android:layout_height = " wrap_content "
          android:layout_alignParentTop = " true " >
           < ImageView
            android:src = " @drawable/star_gray "
            android:layout_width = " wrap_content "
            android:layout_height = " wrap_content "
            android:layout_margin = " 5dip " />
         < TextView
            android:layout_width = " wrap_content "
            android:layout_height = " wrap_content "
            android:text = " 选择任务优先级 "
            android:layout_gravity = " center_vertical " />
       </ LinearLayout >
       < ! -- 任务优先级 -->
       < ListView
          android:id = " @+id/dlg_priority_lvw "
          android:layout_width = " wrap_content "
          android:layout_height = " wrap_content "
          android:layout_below = " @id/dlg_priority_titlebar "
          android:background = " @drawable/layout_home_bg " >
       </ ListView >     
</ RelativeLayout >

  2、因为该布局中使用了自定义的ListView,所以再为ListView创建布局文件

< ?xml version = " 1.0 " encoding = " utf-8 " ? >< LinearLayout    xmlns:android = " http://schemas.android.com/apk/res/android "     android:orientation = " horizontal "     android:layout_width = " fill_parent "     android:layout_height = " fill_parent "      >      < ImageView          android:id = " @+id/list_priority_img "           android:layout_width = " wrap_content "           android:layout_height = " wrap_content "           android:layout_gravity = " center_vertical "           android:layout_margin = " 5dip "                    />      < TextView         android:id = " @+id/list_priority_value "          android:layout_width = " wrap_content "          android:layout_height = " wrap_content "         android:layout_gravity = " center_vertical "          android:textSize = " 28dip "          android:textColor = " @drawable/black " /></ LinearLayout >

 

  3、创建自定义Dialog类PriorityDlg继承自Dialog

public class PriorityDlg extends Dialog {
    
     private Context context;
     private ListView dlg_priority_lvw = null ;

public PriorityDlg(Context context) {
        super(context);
        this.context = context;
         // TODO Auto - generated constructor stub
    }
    
     public PriorityDlg(Context context, int theme) {
        super(context, theme);
        this.context = context;
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
         // TODO Auto - generated method stub
        super.onCreate(savedInstanceState);
       // 设置对话框使用的布局文件
        this.setContentView(R.layout.dlg_priority);

dlg_priority_lvw = (ListView) findViewById(R.id.dlg_priority_lvw);

// 设置ListView的数据源
        SimpleAdapter adapter = new SimpleAdapter(context, getPriorityList(),
                R.layout.lvw_priority, new String [] { " list_priority_img " ,
                         " list_priority_value " }, new int [] {
                        R.id.list_priority_img, R.id.list_priority_value });
        dlg_priority_lvw.setAdapter(adapter);

// 为ListView设置监听器
        dlg_priority_lvw
                .setOnItemClickListener( new AdapterView.OnItemClickListener() {

@Override
                     public void onItemClick(AdapterView < ? > arg0, View arg1,
                             int arg2, long arg3) {

}
                });
    }

/**
     * 得到ListView数据源
     *
     * @return
     */
     private List < HashMap < String , Object >> getPriorityList() {
        List < HashMap < String , Object >> priorityList = new ArrayList < HashMap < String , Object >> ();
        HashMap < String , Object > map1 = new HashMap < String , Object > ();
        map1.put( " list_priority_img " , R.drawable.priority_not_important);
        map1.put( " list_priority_value " , context.getResources().getString(
                R.string.dlg_priority_not_important));
        priorityList.add(map1);
        HashMap < String , Object > map2 = new HashMap < String , Object > ();
        map2.put( " list_priority_img " , R.drawable.priority_general);
        map2.put( " list_priority_value " , context.getResources().getString(
                R.string.dlg_priority_general));
        priorityList.add(map2);
        HashMap < String , Object > map3 = new HashMap < String , Object > ();
        map3.put( " list_priority_img " , R.drawable.priority_important);
        map3.put( " list_priority_value " , context.getResources().getString(
                R.string.dlg_priority_important));
        priorityList.add(map3);
        HashMap < String , Object > map4 = new HashMap < String , Object > ();
        map4.put( " list_priority_img " , R.drawable.priority_very_important);
        map4.put( " list_priority_value " , context.getResources().getString(
                R.string.dlg_priority_very_important));
        priorityList.add(map4);

return priorityList;
    }

}

  4、创建自定义对话框

PriorityDlg dlg = new PriorityDlg(SimpleTaskActivity.this, R.style.dlg_priority);
return dlg;

  这里的R.style.dlg_priority设置了对话框使用的样式文件,只是让对话框去掉标题栏,当然你也可以通过代码来完成这种效果:

< ?xml version = " 1.0 " encoding = " utf-8 " ? >< resources >      < ! -- 对话框样式 -->      < style name = " dlg_priority " parent = " @android:Theme.Dialog " >          < item name = " android:windowNoTitle " > true </ item >      </ style ></ resources >

  

  到这里自定义对话框的创建就结束了,想要什么样子的对话框完全凭你自己的想像。

Android开发中Dialog对话框的使用相关推荐

  1. android黑色半透明dialog背景,Android开发中Dialog半透明背景消失

    近日,遇到一个Dialog半透明背景消失的问题,背景需求是自定义Dialog实现警告提示框: // 初始化警告弹出框 alertDialog = new EmpAlertView(context, U ...

  2. android 中dialog对话框,Android中的对话框dialog

    普通对话框 单选对话框 多选对话框 进度条对话框 底部弹出框 1.普通对话框 this 代表当前类 最终继承Context 相当于是子类 getApplicationContext:直接返回的是Con ...

  3. Android开发中常见的设计模式

    对于开发人员来说,设计模式有时候就是一道坎,但是设计模式又非常有用,过了这道坎,它可以让你水平提高一个档次.而在android开发中,必要的了解一些设计模式又是非常有必要的.对于想系统的学习设计模式的 ...

  4. Android 开发中的日常积累

    Android 性能优化 Android性能优化视频,文档以及工具 胡凯-性能优化 Android最佳性能实践(1):合理管理内存 Android最佳性能实践(2):分析内存的使用情况 Android ...

  5. Android开发中应避免的重大错误

    by Varun Barad 由Varun Barad Android开发中应避免的重大错误 (Critical mistakes to avoid in Android development) A ...

  6. Android开发中使用七牛云存储进行图片上传下载

    Android开发中的图片存储本来就是比较耗时耗地的事情,而使用第三方的七牛云,便可以很好的解决这些后顾之忧,最近我也是在学习七牛的SDK,将使用过程在这记录下来,方便以后使用. 先说一下七牛云的存储 ...

  7. 在Android开发中怎样使用Application类

    转载地址:http://www.jianshu.com/p/3138f9c351e8 --- 在Android开发中怎样使用Application类 自己独立开发项目才发现以前对Application ...

  8. Android底部日期控件,Android开发中实现IOS风格底部选择器(支持时间 日期 自定义)...

    本文Github代码链接 先上图吧: 这是笔者最近一个项目一直再用的一个选择器库,自己也在其中做了修改,并决定持续维护下去. 先看使用方法: 日期选择: private void showDateDi ...

  9. Android开发中的WMS详细解析

    /   今日科技快讯   / 近日,小冰公司宣布对旗下人工智能数字员工产品线启动年度升级.本次升级加强的技术包括大模型对话引擎.3D神经网络渲染.超级自然语音及AIGC人工智能内容生成.小冰公司计划将 ...

最新文章

  1. Spring框架基础知识
  2. gradle sync failed——Android studio 突然就无法自动下载gradle了
  3. (计算机组成原理)第三章存储系统-第六节2:Cache和主存的映射方式(全相联映射、直接映射和组相连映射)
  4. jquery 当页面图片加载之后_图片的懒加载和预加载
  5. colab显示没有gpu的解决方法
  6. 《Java编程的逻辑》终于上市了!,java开发面试笔试题
  7. SDK与API的区别
  8. mysql 事务 返回插入的值_深入理解mysql事务:事务机制的实现原理
  9. 无线移动通信基础知识
  10. (转载)Linux的IPC命令
  11. 20181030函数2
  12. IGMC,Inductive graph-based matrix completion,基于归纳图的矩阵完成
  13. 520用Java制作一个表白app
  14. 国内第一本Julia语言书籍《Julia语言程序设计》出版了!
  15. 无法使用tftp下载Linux内核到开发板,总是显示TTTTTTTTT的原因
  16. IOS调用微信扫一扫scanQRCode报错the permission value is offline verifying
  17. 学习操作系统的关键一步!
  18. 传说中的补丁比较...很好玩啊..
  19. 设计师的AI自学之路:用图像识别玩忍术
  20. 知识图谱入门 (九) 知识问答

热门文章

  1. Recaptured Image Forensics Based on Image Illumination and Texture Features ICVIP2020
  2. 办公室常用的办公软件有哪些
  3. 信息熵对复杂网络中影响节点的识别(Enrenew algroithm)以及SIR模型
  4. 快速排序+改进版(邓俊辉老师讲授)
  5. 苹果cmsv10首涂第二十二套带后台系统原创多功能自适应高端模板
  6. 惠普mini机箱小欧290安装固态硬盘(SSD)过程
  7. IT忍者神龟之XHTML教程
  8. 人工智能编程教育机器人
  9. 无数论坛谈的“社群经济是什么”
  10. 性能优化之道:上万并发下的SpringCloud参数优化实战