Android AlertDialog對話框

1.常見對話框的源碼:

[java] view plain copy
  1. package com.naoh.stu;  
  2.   
  3. import java.util.ArrayList;  
  4.   
  5. import android.app.Activity;  
  6. import android.app.AlertDialog;  
  7. import android.app.ProgressDialog;  
  8. import android.content.DialogInterface;  
  9. import android.graphics.drawable.BitmapDrawable;  
  10. import android.os.Bundle;  
  11. import android.view.Gravity;  
  12. import android.view.LayoutInflater;  
  13. import android.view.View;  
  14. import android.view.View.OnClickListener;  
  15. import android.view.ViewGroup.LayoutParams;  
  16. import android.view.WindowManager;  
  17. import android.widget.Button;  
  18. import android.widget.EditText;  
  19. import android.widget.PopupWindow;  
  20. import android.widget.Toast;  
  21.   
  22. public class DiaAllActivity extends Activity implements Runnable {  
  23.     private Button btn_diaNormal;   
  24.     private Button btn_diaMulti;  
  25.     private Button btn_diaList;  
  26.     private Button btn_diaSinChos;  
  27.     private Button btn_diaMultiChos;  
  28.     private Button btn_diaProcess;  
  29.     private Button btn_diaReadProcess;  
  30.     private Button btn_diaCustom;  
  31.     private Button btn_popUpDia;  
  32.       
  33.     private PopupWindow window=null;  
  34.     private Button cusPopupBtn1;  
  35.     private View popupView;  
  36.   
  37.     @Override  
  38.     public void onCreate(Bundle savedInstanceState)  
  39.     {  
  40.         super.onCreate(savedInstanceState);  
  41.         setContentView(R.layout.dialog);  
  42.         getView();  
  43.         setListener();  
  44.     }  
  45.       
  46.     private void getView()  
  47.     {  
  48.         btn_diaNormal=(Button)findViewById(R.id.btn_diaNormal);  
  49.         btn_diaMulti=(Button)findViewById(R.id.btn_diaMulti);  
  50.         btn_diaList=(Button)findViewById(R.id.btn_diaList);  
  51.         btn_diaSinChos=(Button)findViewById(R.id.btn_diaSigChos);  
  52.         btn_diaMultiChos=(Button)findViewById(R.id.btn_diaMultiChos);  
  53.         btn_diaProcess=(Button)findViewById(R.id.btn_diaProcess);  
  54.         btn_diaReadProcess=(Button)findViewById(R.id.btn_diaReadProcess);  
  55.         btn_diaCustom=(Button)findViewById(R.id.btn_diaCustom);  
  56.         btn_popUpDia=(Button)findViewById(R.id.btn_popUpDia);  
  57.           
  58.     }  
  59.       
  60.     private void setListener()  
  61.     {  
  62.         btn_diaNormal.setOnClickListener(btnListener);  
  63.         btn_diaMulti.setOnClickListener(btnListener);  
  64.         btn_diaList.setOnClickListener(btnListener);  
  65.         btn_diaSinChos.setOnClickListener(btnListener);  
  66.         btn_diaMultiChos.setOnClickListener(btnListener);  
  67.         btn_diaProcess.setOnClickListener(btnListener);  
  68.         btn_diaReadProcess.setOnClickListener(btnListener);  
  69.         btn_diaCustom.setOnClickListener(btnListener);  
  70.         btn_popUpDia.setOnClickListener(btnListener);  
  71.     }  
  72.       
  73.     private Button.OnClickListener btnListener= new Button.OnClickListener()  
  74.     {  
  75.         public void onClick(View v)  
  76.         {  
  77.             if(v instanceof Button)  
  78.             {  
  79.                 int btnId=v.getId();  
  80.                 switch(btnId)  
  81.                 {  
  82.                     case R.id.btn_diaNormal:  
  83.                         showNormalDia();  
  84.                         break;  
  85.                     case R.id.btn_diaMulti:  
  86.                         showMultiDia();  
  87.                         break;  
  88.                     case R.id.btn_diaList:  
  89.                         showListDia();  
  90.                         break;  
  91.                     case R.id.btn_diaSigChos:  
  92.                         showSinChosDia();  
  93.                         break;  
  94.                     case R.id.btn_diaMultiChos:  
  95.                         showMultiChosDia();  
  96.                         break;  
  97.                     case R.id.btn_diaReadProcess:  
  98.                         showReadProcess();  
  99.                         break;  
  100.                     case R.id.btn_diaProcess:  
  101.                         showProcessDia();  
  102.                         break;  
  103.                     case R.id.btn_diaCustom:  
  104.                         showCustomDia();  
  105.                         break;  
  106.                     case R.id.btn_popUpDia:  
  107.                         showCusPopUp(v);  
  108.                         break;  
  109.                     default:  
  110.                         break;  
  111.                 }  
  112.             }  
  113.         }  
  114.     };  
  115.   
  116.     /*普通的對話框*/  
  117.     private void showNormalDia()  
  118.     {  
  119.         //AlertDialog.Builder normalDialog=new AlertDialog.Builder(getApplicationContext());  
  120.         AlertDialog.Builder normalDia=new AlertDialog.Builder(DiaAllActivity.this);  
  121.         normalDia.setIcon(R.drawable.ic_launcher);  
  122.         normalDia.setTitle("普通的對話框");  
  123.         normalDia.setMessage("普通對話框的message內容");  
  124.           
  125.         normalDia.setPositiveButton("確定"new DialogInterface.OnClickListener() {  
  126.             @Override  
  127.             public void onClick(DialogInterface dialog, int which) {  
  128.                 // TODO Auto-generated method stub  
  129.                 showClickMessage("確定");  
  130.             }  
  131.         });  
  132.         normalDia.setNegativeButton("取消"new DialogInterface.OnClickListener() {  
  133.             @Override  
  134.             public void onClick(DialogInterface dialog, int which) {  
  135.                 // TODO Auto-generated method stub  
  136.                 showClickMessage("取消");  
  137.             }  
  138.         });  
  139.         normalDia.create().show();  
  140.     }  
  141.       
  142.     /*多按鈕對話框*/  
  143.     private void showMultiDia()  
  144.     {  
  145.         AlertDialog.Builder multiDia=new AlertDialog.Builder(DiaAllActivity.this);  
  146.         multiDia.setTitle("多選項對話框");  
  147.         multiDia.setPositiveButton("按鈕一"new DialogInterface.OnClickListener() {  
  148.               
  149.             @Override  
  150.             public void onClick(DialogInterface dialog, int which) {  
  151.                 // TODO Auto-generated method stub  
  152.                 showClickMessage("按鈕一");  
  153.             }  
  154.         });  
  155.         multiDia.setNeutralButton("按鈕二"new DialogInterface.OnClickListener() {  
  156.               
  157.             @Override  
  158.             public void onClick(DialogInterface dialog, int which) {  
  159.                 // TODO Auto-generated method stub  
  160.                 showClickMessage("按鈕二");  
  161.             }  
  162.         });  
  163.         multiDia.setNegativeButton("按鈕三"new DialogInterface.OnClickListener() {  
  164.               
  165.             @Override  
  166.             public void onClick(DialogInterface dialog, int which) {  
  167.                 // TODO Auto-generated method stub  
  168.                 showClickMessage("按鈕三");  
  169.             }  
  170.         });  
  171.         multiDia.create().show();  
  172.     }  
  173.       
  174.       
  175.     /*列表對話框*/  
  176.     private void showListDia()  
  177.     {  
  178.         final String[] mList={"選項1","選項2","選項3","選項4","選項5","選項6","選項7"};  
  179.         AlertDialog.Builder listDia=new AlertDialog.Builder(DiaAllActivity.this);  
  180.         listDia.setTitle("列表對話框");  
  181.         listDia.setItems(mList, new DialogInterface.OnClickListener() {  
  182.               
  183.             @Override  
  184.             public void onClick(DialogInterface dialog, int which) {  
  185.                 // TODO Auto-generated method stub  
  186.                 /*下標是從0開始的*/  
  187.                 showClickMessage(mList[which]);  
  188.             }  
  189.         });  
  190.         listDia.create().show();  
  191.     }  
  192.       
  193.     /*單項選擇對話框*/  
  194.     int yourChose=-1;  
  195.     private void showSinChosDia()  
  196.     {  
  197.         final String[] mList={"選項1","選項2","選項3","選項4","選項5","選項6","選項7"};  
  198.         yourChose=-1;  
  199.         AlertDialog.Builder sinChosDia=new AlertDialog.Builder(DiaAllActivity.this);  
  200.         sinChosDia.setTitle("單項選擇對話框");  
  201.         sinChosDia.setSingleChoiceItems(mList, 0new DialogInterface.OnClickListener() {  
  202.               
  203.             @Override  
  204.             public void onClick(DialogInterface dialog, int which) {  
  205.                 // TODO Auto-generated method stub  
  206.                 yourChose=which;  
  207.                   
  208.             }  
  209.         });  
  210.         sinChosDia.setPositiveButton("確定"new DialogInterface.OnClickListener() {  
  211.               
  212.             @Override  
  213.             public void onClick(DialogInterface dialog, int which) {  
  214.                 // TODO Auto-generated method stub  
  215.                 if(yourChose!=-1)  
  216.                 {  
  217.                     showClickMessage(mList[yourChose]);  
  218.                 }  
  219.             }  
  220.         });  
  221.         sinChosDia.create().show();  
  222.     }  
  223.   
  224.     ArrayList<Integer> myChose= new ArrayList<Integer>();  
  225.     private void showMultiChosDia()  
  226.     {  
  227.         final String[] mList={"選項1","選項2","選項3","選項4","選項5","選項6","選項7"};  
  228.         final boolean mChoseSts[]={false,false,false,false,false,false,false};  
  229.         myChose.clear();  
  230.         AlertDialog.Builder multiChosDia=new AlertDialog.Builder(DiaAllActivity.this);  
  231.         multiChosDia.setTitle("多項選擇對話框");  
  232.         multiChosDia.setMultiChoiceItems(mList, mChoseSts, new DialogInterface.OnMultiChoiceClickListener() {  
  233.               
  234.             @Override  
  235.             public void onClick(DialogInterface dialog, int which, boolean isChecked) {  
  236.                 // TODO Auto-generated method stub  
  237.                 if(isChecked)  
  238.                 {  
  239.                     myChose.add(which);  
  240.                 }  
  241.                 else  
  242.                 {  
  243.                     myChose.remove(which);  
  244.                 }  
  245.             }  
  246.         });  
  247.         multiChosDia.setPositiveButton("確定"new DialogInterface.OnClickListener() {  
  248.               
  249.             @Override  
  250.             public void onClick(DialogInterface dialog, int which) {  
  251.                 // TODO Auto-generated method stub  
  252.                 int size=myChose.size();  
  253.                 String str="";  
  254.                 for(int i=0;i<size;i++)  
  255.                 {  
  256.                     str+=mList[myChose.get(i)];  
  257.                 }  
  258.                 showClickMessage(str);  
  259.             }  
  260.         });  
  261.         multiChosDia.create().show();  
  262.     }  
  263.       
  264.     //進度讀取框需要模擬讀取  
  265.     ProgressDialog mReadProcessDia=null;  
  266.     public final static int MAX_READPROCESS = 100;  
  267.     private void showReadProcess()  
  268.     {  
  269.         mReadProcessDia=new ProgressDialog(DiaAllActivity.this);  
  270.         mReadProcessDia.setProgress(0);  
  271.         mReadProcessDia.setTitle("進度條窗口");  
  272.         mReadProcessDia.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
  273.         mReadProcessDia.setMax(MAX_READPROCESS);  
  274.         mReadProcessDia.show();  
  275.         new Thread(this).start();  
  276.     }  
  277.       
  278.     //新開啓一個線程,循環的累加,一直到100然後在停止  
  279.     @Override  
  280.     public void run()  
  281.     {  
  282.         int Progress= 0;  
  283.         while(Progress < MAX_READPROCESS)  
  284.         {  
  285.             try {  
  286.                 Thread.sleep(100);  
  287.                 Progress++;  
  288.                 mReadProcessDia.incrementProgressBy(1);  
  289.             } catch (InterruptedException e) {  
  290.                 // TODO Auto-generated catch block  
  291.                 e.printStackTrace();  
  292.             }  
  293.         }  
  294.         //讀取完了以後窗口自消失  
  295.         mReadProcessDia.cancel();  
  296.     }  
  297.       
  298.     /*讀取中的對話框*/  
  299.     private void showProcessDia()  
  300.     {  
  301.         ProgressDialog processDia= new ProgressDialog(DiaAllActivity.this);  
  302.         processDia.setTitle("進度條框");  
  303.         processDia.setMessage("內容讀取中...");  
  304.         processDia.setIndeterminate(true);  
  305.         processDia.setCancelable(true);  
  306.         processDia.show();  
  307.     }  
  308.       
  309.     /*自定義對話框*/  
  310.     private void showCustomDia()  
  311.     {  
  312.         AlertDialog.Builder customDia=new AlertDialog.Builder(DiaAllActivity.this);  
  313.         final View viewDia=LayoutInflater.from(DiaAllActivity.this).inflate(R.layout.custom_dialog, null);  
  314.         customDia.setTitle("自定義對話框");  
  315.         customDia.setView(viewDia);  
  316.         customDia.setPositiveButton("確定"new DialogInterface.OnClickListener() {  
  317.               
  318.             @Override  
  319.             public void onClick(DialogInterface dialog, int which) {  
  320.                 // TODO Auto-generated method stub  
  321.                 EditText diaInput=(EditText) viewDia.findViewById(R.id.txt_cusDiaInput);  
  322.                 showClickMessage(diaInput.getText().toString());  
  323.             }  
  324.         });  
  325.         customDia.create().show();  
  326.     }  
  327.       
  328.     /*popup window 來實現*/  
  329.     private void showCusPopUp(View parent)  
  330.     {  
  331.         if(window == null)  
  332.         {  
  333.             popupView=LayoutInflater.from(DiaAllActivity.this).inflate(R.layout.dia_cuspopup_dia, null);  
  334.             cusPopupBtn1=(Button)popupView.findViewById(R.id.diaCusPopupSure);  
  335.             window =new PopupWindow(popupView,LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);  
  336.         }  
  337.         window.setAnimationStyle(R.style.PopupAnimation);  
  338.         /*必須調用setBackgroundDrawable, 因爲popupwindow在初始時,會檢測background是否爲null,如果是onTouch or onKey events就不會相應,所以必須設置background*/  
  339.         /*網上也有很多人說,彈出pop之後,不響應鍵盤事件了,這個其實是焦點在pop裏面的view去了。*/  
  340.         window.setFocusable(true);  
  341.         window.setBackgroundDrawable(new BitmapDrawable());   
  342.         window.update();  
  343.         window.showAtLocation(parent, Gravity.CENTER_VERTICAL, 00);  
  344.         cusPopupBtn1.setOnClickListener(new OnClickListener() {  
  345.             @Override  
  346.             public void onClick(View v) {  
  347.                 // TODO Auto-generated method stub  
  348.                 showClickMessage("popup window的確定");  
  349.             }  
  350.         });  
  351.     }  
  352.       
  353.     /*顯示點擊的內容*/  
  354.     private void showClickMessage(String message)  
  355.     {  
  356.         Toast.makeText(DiaAllActivity.this"你選擇的是: "+message, Toast.LENGTH_SHORT).show();  
  357.     }  
  358. }  


佈局,就是一堆的button

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="各種Dialog合集" />  
  11.     <Button   
  12.         android:layout_width="fill_parent"  
  13.         android:layout_height="wrap_content"  
  14.         android:text="普通Dialog"  
  15.         android:id="@+id/btn_diaNormal"/>  
  16.       
  17.     <Button   
  18.         android:layout_width="fill_parent"  
  19.         android:layout_height="wrap_content"  
  20.         android:text="多按鈕Dialog"  
  21.         android:id="@+id/btn_diaMulti"/>  
  22.       
  23.     <Button   
  24.         android:layout_width="fill_parent"  
  25.         android:layout_height="wrap_content"  
  26.         android:text="列表Dialog"  
  27.         android:id="@+id/btn_diaList"/>  
  28.       
  29.     <Button   
  30.         android:layout_width="fill_parent"  
  31.         android:layout_height="wrap_content"  
  32.         android:text="單項選擇Dialog"  
  33.         android:id="@+id/btn_diaSigChos"/>  
  34.       
  35.     <Button   
  36.         android:layout_width="fill_parent"  
  37.         android:layout_height="wrap_content"  
  38.         android:text="多項選擇Dialog"  
  39.         android:id="@+id/btn_diaMultiChos"/>  
  40.       
  41.     <Button   
  42.         android:layout_width="fill_parent"  
  43.         android:layout_height="wrap_content"  
  44.         android:text="進度條Dialog"  
  45.         android:id="@+id/btn_diaReadProcess"/>  
  46.       
  47.     <Button   
  48.         android:layout_width="fill_parent"  
  49.         android:layout_height="wrap_content"  
  50.         android:text="讀取中Dialog"  
  51.         android:id="@+id/btn_diaProcess"/>  
  52.       
  53.     <Button   
  54.         android:layout_width="fill_parent"  
  55.         android:layout_height="wrap_content"  
  56.         android:text="自定義Dialog"  
  57.         android:id="@+id/btn_diaCustom"/>  
  58.       
  59.     <Button   
  60.         android:layout_width="fill_parent"  
  61.         android:layout_height="wrap_content"  
  62.         android:text="PopUpWindow實現的dialog"  
  63.         android:id="@+id/btn_popUpDia"/>  
  64. </LinearLayout>  

2.自定義對話框:

系統默認的AlertDialog,與項目的UI不統一,所以,改了一下,定義了一樣式,最終效果如下圖:

另外,爲了儘量少改原來的代碼,該類類名及相關方法名都與android.app.AlertDialog相同,使用時,原代碼只需要修改導入的包名,在按鈕的Listener上加上一句關閉對話框的方法即可.
先是對話框的XML佈局文件:
test.xml

?
1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >     <!-- 頂部橢園邊緣 -->
    <ImageView        android:layout_width="400dp"        android:layout_height="22dp"        android:src="@drawable/dialog_top" >
    </ImageView>
    <!-- 中間白色背景,兩個TextView,標題和內容,留一個LinearLayout,在代碼中根據調用動態加上按鈕 -->
    <LinearLayout        android:layout_width="400dp"        android:layout_height="wrap_content"        android:background="@drawable/dialog_center"        android:orientation="vertical" >         <TextView android:textColor="#000000"            android:textSize="35dp"            android:gravity="center"            android:id="@+id/title"            android:layout_width="fill_parent"            android:layout_height="wrap_content" />         <TextView android:layout_marginLeft="20dp"            android:layout_marginRight="10dp"            android:id="@+id/message"            android:layout_marginBottom="10dp"            android:layout_marginTop="20dp"            android:textColor="#000000"            android:textSize="25dp"            android:layout_width="fill_parent"            android:layout_height="wrap_content" />
        <!-- 在LinearLayout中加按鈕 -->
        <LinearLayout            android:id="@+id/buttonLayout"            android:layout_width="fill_parent"            android:layout_height="fill_parent"            android:layout_gravity="center"            android:gravity="center"            android:orientation="horizontal" >         </LinearLayout>
    </LinearLayout>
    <!-- 底部橢園邊緣 -->
    <ImageView        android:layout_marginTop="-2dp"        android:layout_width="400dp"        android:layout_height="22dp"        android:src="@drawable/dialog_bottom" >
    </ImageView> </LinearLayout>

按鈕背景,不同狀態不同,可參考本博相關文章:
alertdialog_button.xml

?
1
2
3
4
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" android:drawable="@drawable/dialog_button_pressed" />
    <item android:state_focused="true" android:drawable="@drawable/dialog_button_pressed" />
    <item android:drawable="@drawable/dialog_button" /></selector>

下面就是自定義的AlertDialog類的代碼:

?
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
public class AlertDialog {
    Context context;
    android.app.AlertDialog ad;
    TextView titleView;
    TextView messageView;
    LinearLayout buttonLayout;
    public AlertDialog(Context context) {
        // TODO Auto-generated constructor stub
        this.context=context;
        ad=new android.app.AlertDialog.Builder(context).create();
        ad.show();
        //關鍵在下面的兩行,使用window.setContentView,替換整個對話框窗口的佈局
        Window window = ad.getWindow();
        window.setContentView(R.layout.alertdialog);
        titleView=(TextView)window.findViewById(R.id.title);
        messageView=(TextView)window.findViewById(R.id.message);
        buttonLayout=(LinearLayout)window.findViewById(R.id.buttonLayout);
    }
    public void setTitle(int resId)
    {
        titleView.setText(resId);
    }
    public void setTitle(String title) {
        titleView.setText(title);
    }
    public void setMessage(int resId) {
        messageView.setText(resId);
    public void setMessage(String message)
    {
        messageView.setText(message);
    }
    /**
     * 設置按鈕
     * @param text
     * @param listener
     */
    public void setPositiveButton(String text,final View.OnClickListener listener)
    {
        Button button=new Button(context);
        LinearLayout.LayoutParams params=new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        button.setLayoutParams(params);
        button.setBackgroundResource(R.drawable.alertdialog_button);
        button.setText(text);
        button.setTextColor(Color.WHITE);
        button.setTextSize(20);
        button.setOnClickListener(listener);
        buttonLayout.addView(button);
    /**
     * 設置按鈕
     * @param text
     * @param listener
     */
    public void setNegativeButton(String text,final View.OnClickListener listener)
    {
        Button button=new Button(context);
        LinearLayout.LayoutParams params=new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        button.setLayoutParams(params);
        button.setBackgroundResource(R.drawable.alertdialog_button);
        button.setText(text);
        button.setTextColor(Color.WHITE);
        button.setTextSize(20);
        button.setOnClickListener(listener);
        if(buttonLayout.getChildCount()>0)
        {
            params.setMargins(20000);
            button.setLayoutParams(params);
            buttonLayout.addView(button, 1);
        }else{
            button.setLayoutParams(params);
            buttonLayout.addView(button);
        }  }
    /**
     * 關閉對話框
     */
    public void dismiss() {
        ad.dismiss();
    } }

使用方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
final AlertDialog ad=new AlertDialog(Test.this);
ad.setTitle("標題");
ad.setMessage("內容sdfsafdasf內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容");
ad.setPositiveButton("確定"new OnClickListener() { 
@Override                  
public void onClick(View v) {
    // TODO Auto-generated method stub
    ad.dismiss();
    Toast.makeText(Test.this"被點到確定", Toast.LENGTH_LONG).show();       
}
}); 
ad.setNegativeButton("取消"new OnClickListener() { 
@Override                  
public void onClick(View v) {
// TODO Auto-generated method stub
ad.dismiss();
Toast.makeText(Test.this"被點到取消", Toast.LENGTH_LONG).show();
}
});

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