Dialog,PopWindow,Toast使用场景

本文详细介绍了Android中Material风格Dialog的8种常用类型,包括普通、列表、单选、多选、等待、进度条、编辑和自定义Dialog,并讨论了Dialog的回调函数。同时,对比了Dialog与PopupWindow在设置位置、宽高、动画和显示位置的差异,强调了PopupWindow的便捷性和使用技巧。


Material 风格的 Dialog 的使用  http://www.jianshu.com/p/6caffdbcd5db



以下为:八种形式的Dialog

转载出处:http://www.cnblogs.com/gzdaijie/p/5222191.html

参考文章:http://www.oschina.net/question/54100_32486 其中常见的dialog对话框



Dialog的类型:

2.1 普通Dialog(图1与图2)

2.2 列表Dialog(图3)
2.3 单选Dialog(图4)
2.4 多选Dialog(图5)
2.5 等待Dialog(图6)
2.6 进度条Dialog(图7)

2.7 编辑Dialog(图8)

2.8 自定义Dialog(图9)-----------------(可在此处自定义加载进度的对话框,常见加载网络时弹得对话框)


  • Android提供了丰富的Dialog函数,本文介绍最常用的8种对话框的使用方法,包括普通(包含提示消息和按钮)、列表、单选、多选、等待、进度条、编辑、自定义等多种形式,将在第2部分介绍。
  • 有时,我们希望在对话框创建或关闭时完成一些特定的功能,这需要复写Dialog的create()show()dismiss()等方法,将在第3部分介绍。

2.1 普通Dialog(图1与图2)

  • 2个按钮
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public  class  MainActivity extends  Activity {
 
     @Override
     protected  void  onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         Button buttonNormal = (Button) findViewById(R.id.button_normal);
         buttonNormal.setOnClickListener( new  View.OnClickListener() {
             @Override
             public  void  onClick(View v) {
                 showNormalDialog();
             }
         });
     }
     
     private  void  showNormalDialog(){
         /* @setIcon 设置对话框图标
          * @setTitle 设置对话框标题
          * @setMessage 设置对话框消息提示
          * setXXX方法返回Dialog对象,因此可以链式设置属性
          */
         final  AlertDialog.Builder normalDialog =
             new  AlertDialog.Builder(MainActivity. this );
         normalDialog.setIcon(R.drawable.icon_dialog);
         normalDialog.setTitle( "我是一个普通Dialog" )
         normalDialog.setMessage( "你要点击哪一个按钮呢?" );
         normalDialog.setPositiveButton( "确定" ,
             new  DialogInterface.OnClickListener() {
             @Override
             public  void  onClick(DialogInterface dialog, int  which) {
                 //...To-do
             }
         });
         normalDialog.setNegativeButton( "关闭" ,
             new  DialogInterface.OnClickListener() {
             @Override
             public  void  onClick(DialogInterface dialog, int  which) {
                 //...To-do
             }
         });
         // 显示
         normalDialog.show();
     }
}
  • 3个按钮
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* @setNeutralButton 设置中间的按钮
  * 若只需一个按钮,仅设置 setPositiveButton 即可
  */
private  void  showMultiBtnDialog(){
     AlertDialog.Builder normalDialog =
         new  AlertDialog.Builder(MainActivity. this );
     normalDialog.setIcon(R.drawable.icon_dialog);
     normalDialog.setTitle( "我是一个普通Dialog" ).setMessage( "你要点击哪一个按钮呢?" );
     normalDialog.setPositiveButton( "按钮1" ,
         new  DialogInterface.OnClickListener() {
         @Override
         public  void  onClick(DialogInterface dialog, int  which) {
             // ...To-do
         }
     });
     normalDialog.setNeutralButton( "按钮2" ,
         new  DialogInterface.OnClickListener() {
         @Override
         public  void  onClick(DialogInterface dialog, int  which) {
             // ...To-do
         }
     });
     normalDialog.setNegativeButton( "按钮3" , new  DialogInterface.OnClickListener() {
         @Override
         public  void  onClick(DialogInterface dialog, int  which) {
             // ...To-do
         }
     });
     // 创建实例并显示
     normalDialog.show();
}

2.2 列表Dialog(图3)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private  void  showListDialog() {
     final  String[] items = { "我是1" , "我是2" , "我是3" , "我是4"  };
     AlertDialog.Builder listDialog =
         new  AlertDialog.Builder(MainActivity. this );
     listDialog.setTitle( "我是一个列表Dialog" );
     listDialog.setItems(items, new  DialogInterface.OnClickListener() {
         @Override
         public  void  onClick(DialogInterface dialog, int  which) {
             // which 下标从0开始
             // ...To-do
             Toast.makeText(MainActivity. this ,
                 "你点击了"  + items[which],
                 Toast.LENGTH_SHORT).show();
         }
     });
     listDialog.show();
}

2.3 单选Dialog(图4)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int  yourChoice;
private  void  showSingleChoiceDialog(){
     final  String[] items = { "我是1" , "我是2" , "我是3" , "我是4"  };
     yourChoice = - 1 ;
     AlertDialog.Builder singleChoiceDialog =
         new  AlertDialog.Builder(MainActivity. this );
     singleChoiceDialog.setTitle( "我是一个单选Dialog" );
     // 第二个参数是默认选项,此处设置为0
     singleChoiceDialog.setSingleChoiceItems(items, 0 ,
         new  DialogInterface.OnClickListener() {
         @Override
         public  void  onClick(DialogInterface dialog, int  which) {
             yourChoice = which;
         }
     });
     singleChoiceDialog.setPositiveButton( "确定" ,
         new  DialogInterface.OnClickListener() {
         @Override
         public  void  onClick(DialogInterface dialog, int  which) {
             if  (yourChoice != - 1 ) {
                 Toast.makeText(MainActivity. this ,
                 "你选择了"  + items[yourChoice],
                 Toast.LENGTH_SHORT).show();
             }
         }
     });
     singleChoiceDialog.show();
}

2.4 多选Dialog(图5)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
ArrayList<Integer> yourChoices = new  ArrayList<>();
private  void  showMultiChoiceDialog() {
     final  String[] items = { "我是1" , "我是2" , "我是3" , "我是4"  };
     // 设置默认选中的选项,全为false默认均未选中
     final  boolean  initChoiceSets[]={ false , false , false , false };
     yourChoices.clear();
     AlertDialog.Builder multiChoiceDialog =
         new  AlertDialog.Builder(MainActivity. this );
     multiChoiceDialog.setTitle( "我是一个多选Dialog" );
     multiChoiceDialog.setMultiChoiceItems(items, initChoiceSets,
         new  DialogInterface.OnMultiChoiceClickListener() {
         @Override
         public  void  onClick(DialogInterface dialog, int  which,
             boolean  isChecked) {
             if  (isChecked) {
                 yourChoices.add(which);
             } else  {
                 yourChoices.remove(which);
             }
         }
     });
     multiChoiceDialog.setPositiveButton( "确定" ,
         new  DialogInterface.OnClickListener() {
         @Override
         public  void  onClick(DialogInterface dialog, int  which) {
             int  size = yourChoices.size();
             String str = "" ;
             for  ( int  i = 0 ; i < size; i++) {
                 str += items[yourChoices.get(i)] + " " ;
             }
             Toast.makeText(MainActivity. this ,
                 "你选中了"  + str,
                 Toast.LENGTH_SHORT).show();
         }
     });
     multiChoiceDialog.show();
}

2.5 等待Dialog(图6)

1
2
3
4
5
6
7
8
9
10
11
12
13
private  void  showWaitingDialog() {
     /* 等待Dialog具有屏蔽其他控件的交互能力
      * @setCancelable 为使屏幕不可点击,设置为不可取消(false)
      * 下载等事件完成后,主动调用函数关闭该Dialog
      */
     ProgressDialog waitingDialog=
         new  ProgressDialog(MainActivity. this );
     waitingDialog.setTitle( "我是一个等待Dialog" );
     waitingDialog.setMessage( "等待中..." );
     waitingDialog.setIndeterminate( true );
     waitingDialog.setCancelable( false );
     waitingDialog.show();
}

2.6 进度条Dialog(图7)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
private  void  showProgressDialog() {
     /* @setProgress 设置初始进度
      * @setProgressStyle 设置样式(水平进度条)
      * @setMax 设置进度最大值
      */
     final  int  MAX_PROGRESS = 100 ;
     final  ProgressDialog progressDialog =
         new  ProgressDialog(MainActivity. this );
     progressDialog.setProgress( 0 );
     progressDialog.setTitle( "我是一个进度条Dialog" );
     progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
     progressDialog.setMax(MAX_PROGRESS);
     progressDialog.show();
     /* 模拟进度增加的过程
      * 新开一个线程,每个100ms,进度增加1
      */
     new  Thread( new  Runnable() {
         @Override
         public  void  run() {
             int  progress= 0 ;
             while  (progress < MAX_PROGRESS){
                 try  {
                     Thread.sleep( 100 );
                     progress++;
                     progressDialog.setProgress(progress);
                 } catch  (InterruptedException e){
                     e.printStackTrace();
                 }
             }
             // 进度达到最大值后,窗口消失
             progressDialog.cancel();
         }
     }).start();
}

2.7 编辑Dialog(图8)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private  void  showInputDialog() {
     /*@setView 装入一个EditView
      */
     final  EditText editText = new  EditText(MainActivity. this );
     AlertDialog.Builder inputDialog =
         new  AlertDialog.Builder(MainActivity. this );
     inputDialog.setTitle( "我是一个输入Dialog" ).setView(editText);
     inputDialog.setPositiveButton( "确定" ,
         new  DialogInterface.OnClickListener() {
         @Override
         public  void  onClick(DialogInterface dialog, int  which) {
             Toast.makeText(MainActivity. this ,
             editText.getText().toString(),
             Toast.LENGTH_SHORT).show();
         }
     }).show();
}

2.8 自定义Dialog(图9)

1
2
3
4
5
6
7
8
9
10
11
12
<!-- res/layout/dialog_customize.xml-->
<!-- 自定义View -->
< LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
     < EditText
         android:id="@+id/edit_text"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         />
</ LinearLayout >
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private  void  showCustomizeDialog() {
     /* @setView 装入自定义View ==> R.layout.dialog_customize
      * 由于dialog_customize.xml只放置了一个EditView,因此和图8一样
      * dialog_customize.xml可自定义更复杂的View
      */
     AlertDialog.Builder customizeDialog =
         new  AlertDialog.Builder(MainActivity. this );
     final  View dialogView = LayoutInflater.from(MainActivity. this )
         .inflate(R.layout.dialog_customize, null );
     customizeDialog.setTitle( "我是一个自定义Dialog" );
     customizeDialog.setView(dialogView);
     customizeDialog.setPositiveButton( "确定" ,
         new  DialogInterface.OnClickListener() {
         @Override
         public  void  onClick(DialogInterface dialog, int  which) {
             // 获取EditView中的输入内容
             EditText edit_text =
                 (EditText) dialogView.findViewById(R.id.edit_text);
             Toast.makeText(MainActivity. this ,
                 edit_text.getText().toString(),
                 Toast.LENGTH_SHORT).show();
         }
     });
     customizeDialog.show();
}

3.复写回调函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* 复写Builder的create和show函数,可以在Dialog显示前实现必要设置
  * 例如初始化列表、默认选项等
  * @create 第一次创建时调用
  * @show 每次显示时调用
  */
private  void  showListDialog() {
     final  String[] items = { "我是1" , "我是2" , "我是3" , "我是4"  };
     AlertDialog.Builder listDialog =
         new  AlertDialog.Builder(MainActivity. this ){
         
         @Override
         public  AlertDialog create() {
             items[ 0 ] = "我是No.1" ;
             return  super .create();
         }
 
         @Override
         public  AlertDialog show() {
             items[ 1 ] = "我是No.2" ;
             return  super .show();
         }
     };
     listDialog.setTitle( "我是一个列表Dialog" );
     listDialog.setItems(items, new  DialogInterface.OnClickListener() {
         @Override
         public  void  onClick(DialogInterface dialog, int  which) {
             // ...To-do
         }
     });
     /* @setOnDismissListener Dialog销毁时调用
      * @setOnCancelListener Dialog关闭时调用
      */
     listDialog.setOnDismissListener( new  DialogInterface.OnDismissListener() {
         public  void  onDismiss(DialogInterface dialog) {
             Toast.makeText(getApplicationContext(),
                 "Dialog被销毁了" ,
                 Toast.LENGTH_SHORT).show();
         }
     });
     listDialog.show();
}
PoPWindow的使用
http://blog.csdn.net/eclothy/article/details/39340657
android的系统弹出控件很多,Toast,OptionsMenu,Dialog,PopupWindow等。一大堆的弹出控件,文档又没有明确说出各控件应用于哪些场景,使得实际开发中很多鸡肋,有时候自己花很多力气去尝试做一个弹出控件,结果才发现用错了api接口。
最近在做一个项目,要求用户在title栏中点击button弹出检索框进行搜索。在网上找了很多,最开始想的是用AlertDialog,我要做的效果是弹出框宽度为全屏:match_parent,高度为自适应:wrap_content,底层为背景半透明。但是在学习过的源码中从来没有见到过占满全屏的Dialog弹框,所以想着用PopupWindow来做。

以下根据网上查阅的资料,整理了Dialog和PopupWindow的一些区别,涉及到弹框场景时,以作参考。

AlertDialog和Popupwindow的区别:
1)AlertDialog是非阻塞线程的,Popupwindow是阻塞线程的。
2)Dialog没法设置宽为整个屏幕宽,总有点边界。Popupwindow可以。

1、Dialog及设置Dialog的动画

设置Dialog的位置和大小与加载的布局文件无关。需自己设置dialog参数。
1)设置Dialog位置:

设置位置时必须先指定Dialog的gravity属性,否则指定大小无用。

[java]  view plain  copy
  1. /* 
  2.     * lp.x与lp.y表示相对于原始位置的偏移. 
  3.     * 当参数值包含Gravity.LEFT时,对话框出现在左边,所以lp.x就表示相对左边的偏移,负值忽略. 
  4.     * 当参数值包含Gravity.RIGHT时,对话框出现在右边,所以lp.x就表示相对右边的偏移,负值忽略. 
  5.     * 当参数值包含Gravity.TOP时,对话框出现在上边,所以lp.y就表示相对上边的偏移,负值忽略. 
  6.     * 当参数值包含Gravity.BOTTOM时,对话框出现在下边,所以lp.y就表示相对下边的偏移,负值忽略. 
  7.     * 当参数值包含Gravity.CENTER_HORIZONTAL时 
  8.     * ,对话框水平居中,所以lp.x就表示在水平居中的位置移动lp.x像素,正值向右移动,负值向左移动. 
  9.     * 当参数值包含Gravity.CENTER_VERTICAL时 
  10.     * ,对话框垂直居中,所以lp.y就表示在垂直居中的位置移动lp.y像素,正值向右移动,负值向左移动. 
  11.     * gravity的默认值为Gravity.CENTER,即Gravity.CENTER_HORIZONTAL | 
  12.     * Gravity.CENTER_VERTICAL. 
  13.     *  
  14.     * 本来setGravity的参数值为Gravity.LEFT | Gravity.TOP时对话框应出现在程序的左上角,但在 
  15.     * 我手机上测试时发现距左边与上边都有一小段距离,而且垂直坐标把程序标题栏也计算在内了, 
  16.     * Gravity.LEFT, Gravity.TOP, Gravity.BOTTOM与Gravity.RIGHT都是如此,据边界有一小段距离 
  17. */  
  18. lp.y=90;  

2)去标题:

[java]  view plain  copy
  1. dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);<span style="color:#cc0000;">//要在创建完dialog后就调用,否则报错  

3)设置Dialog的宽和高

[java]  view plain  copy
  1. WindowManager wm = getWindowManager();    
  2. Display display = wm.getDefaultDisplay();    
  3. android.view.WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();       
  4. lp.width = display.getWidth();    
  5. lp.height =LayoutParams.WRAP_CONTENT;    
  6. dialog.getWindow().setAttributes(lp);   

4)设置动画

设置Dialog的动画只能通过设置xml的形式,然后设置在style中,最后在代码中设置。

2)贴代码

第一步:写动画xml

window_in.xml:

[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>      
  2. <set xmlns:android="http://schemas.android.com/apk/res/android" >      
  3. <translate      
  4.         android:duration="500"      
  5.         android:fromXDelta="0"      
  6.         android:fromYDelta="1000"      
  7.         android:toXDelta="0"      
  8.         android:toYDelta="0" />      
  9. </set>   

window_out.xml:

[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>      
  2. <set xmlns:android="http://schemas.android.com/apk/res/android" >      
  3. <translate      
  4.         android:duration="500"      
  5.         android:fromXDelta="0"      
  6.         android:fromYDelta="0"      
  7.         android:toXDelta="0"      
  8.         android:toYDelta="1000" />      
  9. </set>      

第二步:动画配置到style中

[html]  view plain  copy
  1. <style name="main_menu_animstyle">      
  2.        <item name="android:windowEnterAnimation">@anim/settingswindow_in_anim</item>      
  3.        <item name="android:windowExitAnimation">@anim/settingswindow_out_anim</item>      
  4. </style>   

第三步:将动画用于dialog中

[html]  view plain  copy
  1. Window window = dialog.getWindow();      
  2. //设置显示动画      
  3. window.setWindowAnimations(R.style.main_menu_animstyle);      
  4. WindowManager.LayoutParams wl = window.getAttributes();      
  5. wl.x = 0;      
  6. wl.y = getWindowManager().getDefaultDisplay().getHeight();      
  7. //设置显示位置      
  8. dialog.onWindowAttributesChanged(wl);//设置点击外围解散      
  9. dialog.setCanceledOnTouchOutside(true);      
  10. dialog.show();  

2、Popupwindow

1)设置显示位置特别方便:

showAsDropDown(View anchor):相对某个控件的位置(正左下方),无偏移。
showAsDropDown(View anchor, int xoff, int yoff):相对某个控件的位置,有偏移。
showAtLocation(View parent, int gravity, int x, int y):相对于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移。

2)点击Popupwindow以外区域自动消失

注意一定要设置backgroundDrawable

[java]  view plain  copy
  1. //参数也可以是下面这俩值    
  2. //1、getResources().getDrawable(R.drawable.abc)    
  3. //2、getWallpaper()    
  4. //当你发现有背景色时,需给布局文件设置背景色,这样即可覆盖系统自带的背景色。    
  5. pw.setBackgroundDrawable(new BitmapDrawable());    
  6. pw.setOutsideTouchable(true);    
有种说法是pw.setFocusable(false);,则不点击区域以外不会消失。经测试,此种说法不对。

3)完整用法贴代码:

[java]  view plain  copy
  1. View view=LayoutInflater.from(MainActivity.this).inflate(R.layout.popup, null);    
  2. PopupWindow pw=new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,300);    
  3. //  pw.setFocusable(true);------完全没用啊    
  4. //参数也可以是下面这俩值    
  5. //1、getResources().getDrawable(R.drawable.abc)    
  6. //2、getWallpaper()    
  7. //当你发现有背景色时,需给布局文件设置背景色,这样即可覆盖系统自带的背景色。    
  8. pw.setBackgroundDrawable(new BitmapDrawable());    
  9. pw.setOutsideTouchable(true);    
  10. pw.showAsDropDown(findViewById(R.id.btn), 0,50);    
  11. //pw.showAtLocation(findViewById(R.id.btn), Gravity.BOTTOM, 0, 0);   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值