Android AlertDialog,PopupWindow,DatePickerDialog,ProgressDialog的详细介绍

来源:互联网 发布:伊甸园ydy论坛广州域名 编辑:程序博客网 时间:2024/06/05 19:14

转载请备注出自于:http://blog.csdn.net/qq_22118507/article/details/51524086


1.AlertDialog对话框

AlertDialog的构造方法全部是Protected的,所以不能直接通过new一个AlertDialog来创建出一个AlertDialog。要创建一个AlertDialog,就要用到AlertDialog.Builder中的create()方法。

使用AlertDialog.Builder创建对话框需要了解以下几个方法:

      setTitle :为对话框设置标题
        setIcon :为对话框设置图标
        setMessage:为对话框设置内容
        setView: 给对话框设置自定义样式
        setItems :设置对话框要显示的一个list,一般用于显示几个命令时
        setMultiChoiceItems :用来设置对话框显示一系列的复选框
        setNeutralButton :普通按钮

        setPositiveButton :给对话框添加"Yes"按钮
        setNegativeButton :对话框添加"No"按钮
        create : 创建对话框
        show :显示对话框

(1)普通框

       AlertDialog.Builder builder = new AlertDialog.Builder(MainDialog.this);           

  1. builder.setIcon(R.drawable.icon);  
  2. builder.setTitle("投票");  
  3. builder.setMessage("您认为什么样的内容能吸引您?");  
  4. builder.setPositiveButton("确定"new DialogInterface.OnClickListener() {  
  5.     public void onClick(DialogInterface dialog, int whichButton) {  
  6.         
  7.     }  
  8. });  
  9. builder.setNeutralButton("忽略"new DialogInterface.OnClickListener() {  
  10.     public void onClick(DialogInterface dialog, int whichButton) {  
  11.                            
  12.     }  
  13. });  
  14. builder.setNegativeButton("取消"new DialogInterface.OnClickListener() {  
  15.     public void onClick(DialogInterface dialog, int whichButton) {  
  16.            
  17.     }  
  18. });  
  19. builder.create().show();  
    (2)列表框

这个数组用于列表选择

  1. final String[] mItems = {"项目1","项目2","项目3","项目4","项目5","项目6","项目7"};  
  1. AlertDialog.Builder builder = new AlertDialog.Builder(MainDialog.this);   
  2.         builder.setTitle("列表选择框");  
  3.         builder.setItems(mItems, new DialogInterface.OnClickListener() {  
  4.             public void onClick(DialogInterface dialog, int which) {  
  5.                 //点击后弹出窗口选择了第几项  
  6.                  
  7.             }  
  8.         });  
  9.         builder.create().show();  
(3)单项选择列表框

mSingleChoice 用于记录单选中的ID

  1. final String[] mItems = {"item0","item1","itme2","item3","itme4","item5","item6"}; 
  1. AlertDialog.Builder builder = new AlertDialog.Builder(MainDialog.this);   
  2.   
  3. mSingleChoiceID = -1;  
  4. builder.setIcon(R.drawable.icon);  
  5.     builder.setTitle("单项选择");  
  6.     builder.setSingleChoiceItems(mItems, 0new DialogInterface.OnClickListener() {  
  7.         public void onClick(DialogInterface dialog, int whichButton) {  
  8.                 mSingleChoiceID = whichButton;  
  9.                 
  10.         }  
  11.     });  
  12.     builder.setPositiveButton("确定"new DialogInterface.OnClickListener() {  
  13.         public void onClick(DialogInterface dialog, int whichButton) {  
  14.             if(mSingleChoiceID > 0) {  
  15.             
  16.             }  
  17.         }  
  18.     });  
  19.     builder.setNegativeButton("取消"new DialogInterface.OnClickListener() {  
  20.         public void onClick(DialogInterface dialog, int whichButton) {  
  21.   
  22.         }  
  23.     });  
  24.    builder.create().show();  
    (4)多项选择列表框

                 

                 

      MultiChoiceID 用于记录多选选中的id号 存在ArrayList中
         选中后 add 进
ArrayList
         取消选中后 remove 出ArrayList


  1. ArrayList <Integer>MultiChoiceID = new ArrayList <Integer>();  

  1. AlertDialog.Builder builder = new AlertDialog.Builder(MainDialog.this);   
  2.   
  3. MultiChoiceID.clear();  
  4. builder.setIcon(R.drawable.icon);  
  5.     builder.setTitle("多项选择");  
  6.     builder.setMultiChoiceItems(mItems,  
  7.             new boolean[]{falsefalsefalsefalsefalsefalsefalse},  
  8.             new DialogInterface.OnMultiChoiceClickListener() {  
  9.                 public void onClick(DialogInterface dialog, int whichButton,  
  10.                         boolean isChecked) {  
  11.                    if(isChecked) {  
  12.                        MultiChoiceID.add(whichButton);  
  13.                        showDialog("你选择的id为" + whichButton + " , " + mItems[whichButton]);  
  14.                    }else {  
  15.                        MultiChoiceID.remove(whichButton);  
  16.                    }  
  17.                       
  18.                 }  
  19.             });  
  20.     builder.setPositiveButton("确定"new DialogInterface.OnClickListener() {  
  21.         public void onClick(DialogInterface dialog, int whichButton) {  
  22.             String str = "";  
  23.             int size = MultiChoiceID.size();  
  24.             for (int i = 0 ;i < size; i++) {  
  25.             str+= mItems[MultiChoiceID.get(i)] + ", ";  
  26.             }  
  27.             showDialog("你选择的是" + str);  
  28.         }  
  29.     });  
  30.     builder.setNegativeButton("取消"new DialogInterface.OnClickListener() {  
  31.         public void onClick(DialogInterface dialog, int whichButton) {  
  32.   
  33.         }  
  34.     });  
  35.    builder.create().show();  
     (5)自定义布局

  1. AlertDialog.Builder builder = new AlertDialog.Builder(MainDialog.this);   
  2.  LayoutInflater factory = LayoutInflater.from(this);  
  3.  final View textEntryView = factory.inflate(R.layout.test, null);  
  4.      builder.setIcon(R.drawable.icon);  
  5.      builder.setTitle("自定义输入框");  
  6.      builder.setView(textEntryView);  
  7.      builder.setPositiveButton("确定"new DialogInterface.OnClickListener() {  
  8.          public void onClick(DialogInterface dialog, int whichButton) {  
  9.            
  10.          EditText userName = (EditText) textEntryView.findViewById(R.id.etUserName);  
  11.          EditText password = (EditText) textEntryView.findViewById(R.id.etPassWord);  
  12.          showDialog("姓名 :"  + userName.getText().toString()  + "密码:" + password.getText().toString() );  
  13.          }  
  14.      });  
  15.      builder.setNegativeButton("取消"new DialogInterface.OnClickListener() {  
  16.          public void onClick(DialogInterface dialog, int whichButton) {  
  17.   
  18.          }  
  19.      });  
  20.    builder.create().show();  


  test.xml布局文件:


  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3. android:layout_height="wrap_content"   
  4. android:layout_width="wrap_content"  
  5. android:orientation="horizontal"  
  6. android:id="@+id/dialog">  
  7. <LinearLayout  
  8. android:layout_height="wrap_content"   
  9. android:layout_width="wrap_content"  
  10. android:orientation="horizontal"  
  11. android:id="@+id/dialogname">  
  12.   
  13. <TextView android:layout_height="wrap_content"  
  14.    android:layout_width="wrap_content"  
  15.   android:id="@+id/tvUserName"   
  16.   android:text="姓名:" />  
  17. <EditText android:layout_height="wrap_content"  
  18.   android:layout_width="wrap_content"   
  19.   android:id="@+id/etUserName"   
  20.   android:minWidth="200dip"/>  
  21. </LinearLayout>    
  22. <LinearLayout  
  23. android:layout_height="wrap_content"   
  24. android:layout_width="wrap_content"  
  25. android:orientation="horizontal"  
  26. android:id="@+id/dialognum"  
  27.  android:layout_below="@+id/dialogname"  
  28. >  
  29.   <TextView android:layout_height="wrap_content"  
  30.    android:layout_width="wrap_content"  
  31.   android:id="@+id/tvPassWord"   
  32.   android:text="密码:" />  
  33. <EditText android:layout_height="wrap_content"  
  34.   android:layout_width="wrap_content"   
  35.   android:id="@+id/etPassWord"   
  36.   android:minWidth="200dip"/>  
  37.  </LinearLayout>    
  38. </RelativeLayout>
  39.   


 2.DatePickerDialog日期对话框

layout中datepickerdialog.xml代码如下:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:layout_width="match_parent"
  4.     android:layout_height="match_parent"
  5.     android:orientation="vertical" 
  6.     android:background="#ffffffff"
  7.     >
  8.     <TextView
  9.         android:layout_width="wrap_content"
  10.         android:layout_height="wrap_content"
  11.         android:id="@+id/showtime"
  12.         android:textColor="#ff000000"
  13.           android:text=""
  14.         />
  15.     <Button
  16.      android:layout_width="wrap_content"
  17.         android:layout_height="wrap_content"
  18.         android:id="@+id/setdate"
  19.         android:text="@string/setdate"
  20.    />

其activity实现如下:

  1. package com.example.testview;

  2. import java.util.Calendar;
  3. import java.util.Date;
  4. import java.util.Locale;

  5. import android.app.Activity;
  6. import android.os.Bundle;
  7. import android.widget.Button;
  8. import android.widget.DatePicker;
  9. import android.widget.TextView;
  10. import android.view.View;
  11. import android.view.View.OnClickListener;
  12. import android.app.DatePickerDialog;

  13. /**
  14.  * 
  15.  * DatePickerDialog是设置日期对话框,通过OnDateSetListener监听并重新设置日期,
  16.  * 当日期被重置后,会执行OnDateSetLintener类中的方法onDateSet()
  17.  *
  18.  */


  19. public class DatePickerDialogExample extends Activity {
  20.     
  21.     private TextView showdate;
  22.     private Button setdate;
  23.     private int year;
  24.     private int month;
  25.     private int day;
  26.     

  27.     @Override
  28.     public void onCreate(Bundle savedInstanceState)
  29.     {
  30.         super.onCreate(savedInstanceState);
  31.         setContentView(R.layout.datepickerdialog);
  32.         
  33.         showdate=(TextView) this.findViewById(R.id.showtime);
  34.         setdate=(Button) this.findViewById(R.id.setdate);
  35.         //初始化Calendar日历对象
  36.         Calendar mycalendar=Calendar.getInstance(Locale.CHINA);
  37.         Date mydate=new Date(); //获取当前日期Date对象
  38.         mycalendar.setTime(mydate);////为Calendar对象设置时间为当前日期
  39.         
  40.         year=mycalendar.get(Calendar.YEAR); //获取Calendar对象中的年
  41.         month=mycalendar.get(Calendar.MONTH);//获取Calendar对象中的月
  42.         day=mycalendar.get(Calendar.DAY_OF_MONTH);//获取这个月的第几天
  43.         showdate.setText("当前日期:"+year+"-"+(month+1)+"-"+day); //显示当前的年月日
  44.         
  45.         //添加单击事件--设置日期
  46.         setdate.setOnClickListener(new OnClickListener(){
  47.             
  48.             @Override
  49.             public void onClick(View v)
  50.             {
  51.                 /**
  52.                  * 构造函数原型:
  53.                  * public DatePickerDialog (Context context, DatePickerDialog.OnDateSetListener callBack, 
  54.                  * int year, int monthOfYear, int dayOfMonth) 
  55.                  * content组件运行Activity,
  56.                  * DatePickerDialog.OnDateSetListener:选择日期事件
  57.                  * year:当前组件上显示的年,monthOfYear:当前组件上显示的月,dayOfMonth:当前组件上显示的第几天
  58.                  * 
  59.                  */
  60.                 //创建DatePickerDialog对象
  61.                 DatePickerDialog dpd=new DatePickerDialog(DatePickerDialogExample.this,Datelistener,year,month,day);
  62.                 dpd.show();//显示DatePickerDialog组件
  63.             }
  64.         });    
  65.         
  66.     }
  67.     private DatePickerDialog.OnDateSetListener Datelistener=new DatePickerDialog.OnDateSetListener()
  68.     {
  69.         /**params:view:该事件关联的组件
  70.          * params:myyear:当前选择的年
  71.          * params:monthOfYear:当前选择的月
  72.          * params:dayOfMonth:当前选择的日
  73.          */
  74.         @Override
  75.         public void onDateSet(DatePicker view, int myyear, int monthOfYear,int dayOfMonth) {
  76.             
  77.             
  78.             //修改year、month、day的变量值,以便以后单击按钮时,DatePickerDialog上显示上一次修改后的值
  79.             year=myyear;
  80.             month=monthOfYear;
  81.             day=dayOfMonth;
  82.             //更新日期
  83.             updateDate();
  84.             
  85.         }
  86.         //当DatePickerDialog关闭时,更新日期显示
  87.         private void updateDate()
  88.         {
  89.             //在TextView上显示日期
  90.             showdate.setText("当前日期:"+year+"-"+(month+1)+"-"+day);
  91.         }
  92.     };
  93.     
  94.     
  95. }

3.自定义对话框

public class SelectDialog extends AlertDialog{

   public SelectDialog(Context context, int theme) {
    super(context, theme);
   }

   public SelectDialog(Context context) {
       super(context);
   }

   public setContentView(int view) {
    setContentView(int view);
   }


   }

颜色color.xml代码

 <?xml version="1.0" encoding="utf-8"?>

<resources>
  
<color name="transparent">#00000000</color>
</resources>

 

样式style.xml代码

 <?xml version="1.0" encoding="utf-8"?>

<resources>
    
<style name="dialog" parent="@android:style/Theme.Dialog">
        
<item name="android:windowFrame">@null</item><!--边框-->
        
<item name="android:windowIsFloating">true</item><!--是否浮现在activity之上-->
        
<item name="android:windowIsTranslucent">false</item><!--半透明-->
        
<item name="android:windowNoTitle">true</item><!--无标题-->
        <item name="android:windowBackground">@color/transparent</item><!--背景透明-->
        
<item name="android:backgroundDimEnabled">false</item><!--模糊-->
    
</style>
</resources>

显示对话框位置和大小

SelectDialog dialog= new SelectDialog(this,R.style.dialog);//创建Dialog并设置样式主题
dialog.setContentView(R.layout.dialog_layout);

dialog.setTitle("Custom Dialog");

/*
* 获取圣诞框的窗口对象及参数对象以修改对话框的布局设置,
* 可以直接调用getWindow(),表示获得这个Activity的Window
* 对象,这样这可以以同样的方式改变这个Activity的属性.
*/
Window dialogWindow = dialog.getWindow();
WindowManager.LayoutParams lp = dialogWindow.getAttributes();
dialogWindow.setGravity(Gravity.LEFT | Gravity.TOP);

/*
* lp.x与lp.y表示相对于原始位置的偏移.
* 当参数值包含Gravity.LEFT时,对话框出现在左边,所以lp.x就表示相对左边的偏移,负值忽略.
* 当参数值包含Gravity.RIGHT时,对话框出现在右边,所以lp.x就表示相对右边的偏移,负值忽略.
* 当参数值包含Gravity.TOP时,对话框出现在上边,所以lp.y就表示相对上边的偏移,负值忽略.
* 当参数值包含Gravity.BOTTOM时,对话框出现在下边,所以lp.y就表示相对下边的偏移,负值忽略.
* 当参数值包含Gravity.CENTER_HORIZONTAL时
* ,对话框水平居中,所以lp.x就表示在水平居中的位置移动lp.x像素,正值向右移动,负值向左移动.
* 当参数值包含Gravity.CENTER_VERTICAL时
* ,对话框垂直居中,所以lp.y就表示在垂直居中的位置移动lp.y像素,正值向右移动,负值向左移动.
* gravity的默认值为Gravity.CENTER,即Gravity.CENTER_HORIZONTAL |
* Gravity.CENTER_VERTICAL.
*
* 本来setGravity的参数值为Gravity.LEFT | Gravity.TOP时对话框应出现在程序的左上角,但在
* 我手机上测试时发现距左边与上边都有一小段距离,而且垂直坐标把程序标题栏也计算在内了,
* Gravity.LEFT, Gravity.TOP, Gravity.BOTTOM与Gravity.RIGHT都是如此,据边界有一小段距离
*/
lp.x = 100; // 新位置X坐标
lp.y = 100; // 新位置Y坐标
lp.width = 300; // 宽度
lp.height = 300; // 高度
lp.alpha = 0.7f; // 透明度

// 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
// dialog.onWindowAttributesChanged(lp);
dialogWindow.setAttributes(lp);

/*
* 将对话框的大小按屏幕大小的百分比设置
*/
// WindowManager m = getWindowManager();
// Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
// WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
// p.height = (int) (d.getHeight() * 0.6); // 高度设置为屏幕的0.6
// p.width = (int) (d.getWidth() * 0.65); // 宽度设置为屏幕的0.65
// dialogWindow.setAttributes(p);
dialog.setCanceledOnTouchOutside(true);//设置点击Dialog外部任意区域关闭Dialog
dialog.show();
4.PopupWindow对话框
public class PopUpActivity extends Activity {      /** Called when the activity is first created. */     @Override     public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.main);          LayoutInflater inflater = LayoutInflater.from(this);          // 引入窗口配置文件          View view = inflater.inflate(R.layout.main2, null);          // 创建PopupWindow对象          final PopupWindow pop = new PopupWindow(view, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);          Button btn = (Button) findViewById(R.id.btn);          // 需要设置一下此参数,点击外边可消失          pop.setBackgroundDrawable(new BitmapDrawable());          //设置点击窗口外边窗口消失          pop.setOutsideTouchable(true);          // 设置此参数获得焦点,否则无法点击          pop.setFocusable(true);  
      pop.getContentView().setOnKeyListener(new OnKeyListener() {
  @Override            
       public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0
                        && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (pop!= null && pop.isShowing()) {                        pop.dismiss();                    }
                    return true;                }
                return false;            }
        });
 @Override    public boolean onKeyDown(int keyCode, KeyEvent event) {        if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {            if (pop!= null && !pop.isShowing()) {                pop.showAtLocation(findViewById(R.id.layout_main), Gravity.BOTTOM, 0, 0);            }            return true;        }        return super.onKeyDown(keyCode, event);    }
}
这样点击菜单键会弹出自定义的PopupWindow,点击空白处或者返回键、菜单键,PopupWindow会消失。

很多时候我们把PopupWindow用作自定义的菜单,需要一个从底部向上弹出的效果,这就需要为PopupWindow添加动画。

在工程res下新建anim文件夹,在anim文件夹先新建两个xml文件

menu_bottombar_in.xml

复制代码
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" >    <translate        android:duration="250"        android:fromYDelta="100.0%"        android:toYDelta="0.0" /></set>
复制代码

menu_bottombar_out.xml

复制代码
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" >    <translate        android:duration="250"        android:fromYDelta="0.0"        android:toYDelta="100%" /></set>
复制代码

在res/value/styles.xml添加一个sytle

    <style name="anim_menu_bottombar">        <item name="android:windowEnterAnimation">@anim/menu_bottombar_in</item>        <item name="android:windowExitAnimation">@anim/menu_bottombar_out</item>    </style>
PopupWindow显示位置的方法介绍:
PopupWindow的显示及位置设置
1.
window.showAtLocation(parent, Gravity.RIGHT | Gravity.BOTTOM10,10);
第一个参数指定PopupWindow的锚点view,即依附在哪个view上。
第二个参数指定起始点为parent的右下角,第三个参数设置以parent的右下角为原点,向左、上各偏移10像素。
2.
1
2
3
4
//将PopupWindow作为anchor的下拉窗口显示。即在anchor的左下角显示
window.showAsDropDown(anchor);
//xoff,yoff基于anchor的左下角进行偏移。
window.showAsDropDown(anchor, xoff, yoff);
如果没有充足的空间显示PopupWindow,那么PopupWindow的左下角将位于anchor的左上角来显示。



1 0
原创粉丝点击