Android AlertDialog,PopupWindow,DatePickerDialog,ProgressDialog的詳細介紹

轉載請備註出自於: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的左上角來顯示。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章