關於AlertDialog 的一些用法

來源:互聯網
上載者:User
建立Dialog1.分類(1)AlertDialog.它能夠管理0個`1個`2個`3個按鈕和一個包含radio或者checkbox的可選項列表.(2)ProgressDialog.一個用於顯示進度圈或者進度條的dialog,繼承自AlertDialog,所以它也支援按鈕.(3)DatePickerDialog.用於讓使用者選擇日期的dialog.(4)TimePickerDialog.用於讓使用者選擇時間的dialog.如果你需要定義自己的dialog,只需要繼承dialog或者上面提到四個組件之一, 並且為新的dialog定義自己的布局就可以了.2.顯示dialog(1)一個dialog總是作為某個Activity的一部分被建立和顯示.建立dialog當然是在Activity的onCreateDialog方法裡做了,但是在建立不同用途的dialog卻有章可循,推薦的方式是使用switch...case...結構.比如一個遊戲裡可能需要暫停和結束兩種dialog,那我們的範例程式碼如下:static final int DIALOG_PAUSED_ID = 0;static final int DIALOG_GAMEOVER_ID = 1;protected Dialog onCreateDialog(int id) {Dialog dialog;switch(id) {case DIALOG_PAUSED_ID:// do the work to define the pause Dialogbreak;case DIALOG_GAMEOVER_ID:// do the work to define the game over Dialogbreak;default:dialog = null;}return dialog;}(2)當你想顯示一個dialog的時候,使用showDialog(int id),參數id是你要顯示的dialog的ID.(3)如果想在每次開啟dialog的時候顯示的內容有所不同,你應該考慮使用onPrepareDialog(int,Dialog)方法.它會在每次開啟dialog時被調用,而不是像onCreateDialog那樣只在建立時被調用.(4)注意:如果你在onCreateDialog方法之外建立一個dialog,它不會預設被綁定到當前的Activity,但是你可以通過setOwnerActivity(Activity)方法來強制綁定.3.關閉dialog(1)當你打算關閉一個dialog時,在dialog對象上調用dismiss()方法或者直接在Activity裡調用dismissDialog(int)方法都可以達到這個目的.實際上他倆是完全一樣的,下面是dismissDialog方法的代碼:public final void dismissDialog(int id) {if (mManagedDialogs == null) {throw missingDialog(id);}final Dialog dialog = mManagedDialogs.get(id);if (dialog == null) {throw missingDialog(id);}dialog.dismiss();}(如果你正在使用onCreateDialog(int)方法管理你所有的dialog的狀態),每次使用dismissDialog(int)方法關閉dialog時,Activity還會保留此dialog的狀態.如果你確信不再需要已經關閉的dialog對象或者清除先前的狀態對你的程式非常重要,那麼你應該使用removeDialog(int),它會清除所有指向這個dialog對象的引用並且關閉它(如果這個dialog正在顯示的話).下面是removeDialog方法的代碼:public final void removeDialog(int id) {if (mManagedDialogs == null) {return;}final Dialog dialog = mManagedDialogs.get(id);if (dialog == null) {return;}dialog.dismiss();mManagedDialogs.remove(id);//這句做了些什麼呢,還沒仔細看}(2)使用dismiss listeners如果想在關閉dialog的時候執行某些程式,那你應該考慮使用DialogInterface.OnDismissListener.使用方法如下代碼所示:Dialog dialog = new Dialog(this);dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {public void onDismiss(DialogInterface dialog) {// write your performance here }});dialog也有cancel狀態,這是一種較特殊的情況.當使用者點擊"返回","取消"或者程式裡明確調用了dialog.cancel()方法時發生.注意,這個時候,先前註冊的OnDismissListener仍然會被通知(即觸發調用).如果你想發出明確的取消通知(而不是簡單的關閉),那你就應該使用setOnCancelListener()方法註冊一個DialogInterface.OnCancelListener來做這件事.4.建立一個AlertDialogAlertDialog類繼承於 Dialog 類.它是系統推薦的方式,能夠構造出使用者介面上的大多數dialog.有如下任何一個需求時,你應該考慮使用它:顯示一列名文本;顯示一段簡訊;讓使用者選擇由一個`兩個或者三個按鈕代表的操作;顯示一個可選項列表(checkbox button或者radio button)AlertDialog.Builder子類用來建立一個AlertDialog.首先使用new AlertDialog.Builder(this)來建立一個Builder對象,然後使用它的公有介面方法設定AlertDialog的所有屬性.完成後可以通過builder.create()來得到新建立的dialog.下面是使用AlertDialog.Builder類來建立不同的AlertDialog的方法:(1)帶button的DialogAlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setMessage("Are you sure you want to exit?").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int id) {MyActivity.this.finish();}}).setNegativeButton("No", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int id) {dialog.cancel();}});AlertDialog alert = builder.create();注意:這裡的按鈕有三類setPositiveButton,setNegativeButton,setNeutralButton, 每一類只允許添加一次, 也就是最多三個按鈕.按鈕的種類名稱只是協助我們區分對待它們,與它們的實際功能(由我們自己在onClick方法裡定義)無關.(2)添加一個列表這個比較簡單,給出程式碼範例final CharSequence[] items = {"Red", "Green", "Blue"};AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setTitle("Pick a color");builder.setItems(items, new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int item) {Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();}});AlertDialog alert = builder.create();(3)添加checkbox 和 radio 按鈕在dialog裡建立多選和單選列表應分別使用setMultiChoiceItems()和setSingleChoiceItems()方法.下面是建立一個單選項列表的代碼:final CharSequence[] items = {"Red", "Green", "Blue"};AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setTitle("Pick a color");builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int item) {Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();}});AlertDialog alert = builder.create();其中,setSingleChoiceItems()方法裡第二個參數的意思是預設時選中哪一項,-1表示預設不選中任何一項.注意:這樣的情況下,使用者可能希望這些值能被記憶並且恢複.要持久化儲存這些選項的值,須藉助android的資料存取技術.(4)建立ProgressDialogProgressDialog dialog = ProgressDialog.show(MyActivity.this, "", "Loading. Please wait...", true);第一個參數為應用程式的Context(上下文);第二個參數為dialog的title;第三個參數是要顯示的訊息文本;the last parameter is whether the progress is indeterminate.ProgressDialog的預設樣式是一個旋轉的輪子.如果要建立一個能顯示即時進度的工具條,需要更多一點的代碼:ProgressDialog progressDialog;progressDialog = new ProgressDialog(mContext);progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);progressDialog.setMessage("Loading...");progressDialog.setCancelable(false);這個代碼在我測試的時候不能直接運行,會報出以下異常:E/AndroidRuntime(  278): Uncaught handler: thread main exiting due to uncaught exceptionE/AndroidRuntime(  278): android.view.WindowManager$BadTokenException: Unable to add window -- token解決辦法是把第二行換成下面這樣就可以了:progressDialog = new ProgressDialog(DialogActivity.this);//這裡要寫程式中Activity的名字(5)建立自訂的Dialog根據使用基類的不同可以分作兩類:使用Dialog類構造;使用AlertDialog類構造兩種類別的不同在於,前者的Title不可為空.如果你不設定title裡的文字,它佔據的空間會空著,這樣顯然不美觀.而用後面一種方法就不會出現這種問題,不設定title,Dialog裡就不顯示,不影響美觀.所以,還是回到那句話,更推薦使用AlertDialog組件.5.介面收集(1)Activity裡與其相關的方法:protected Dialog onCreateDialog(int id)protected void onPrepareDialog(int id, Dialog dialog)public final void showDialog(int id)public final void dismissDialog(int id)public final void removeDialog(int id)(2)android.content.DialogInterface:interface OnCancelListenerinterface OnDismissListenerinterface OnShowListenerinterface OnClickListenerinterface OnMultiChoiceClickListenerinterface OnKeyListener(3)/android-src/frameworks/base/core/java/android/app/Dialog.java類及其子類裡的所有方法一下是自己實現的一下代碼用到了上面所說的一些東西,貼出來希望對網友有一些協助package ff.ff;import android.app.Activity;import android.app.AlertDialog;import android.app.Dialog;import android.content.DialogInterface;import android.os.Bundle;import android.os.Handler;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;//此處要注意一下,最好匯入此包,將之前置入的監聽器包刪掉,自己匯入此包,那麼程式就沒問題了import android.widget.Button;import android.widget.ListView;public class PhoneTest extends Activity implements OnClickListener { private final int DIALOG_DELLETE_FILM = 1; private final int DIALOG_SIMPLE_LIST = 2; private final int DIALOG_SINGLE_CHOICE_LIST = 3; private final int DIALOG_MULTI_CHIOCE_LIST = 4; private String[] provinces = new String[] { "陝西省", "湖南省", "河北省", "四川省",   "廣東省", "山東省" }; private ButtonOnClick buttonOnClick = new ButtonOnClick(1); private ListView lv = null; @Override public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.main);    Button btnDeleteFile = (Button)findViewById(R.id.btnDeleteFile);  btnDeleteFile.setOnClickListener(this);  Button btnSimapleList = (Button)findViewById(R.id.btnSimapleList);  btnSimapleList.setOnClickListener(this);  Button btnSingleChoiceList = (Button)findViewById(R.id.btnSingleChoiceList);  btnSingleChoiceList.setOnClickListener(this);  System.out.println("執行到我了!");  Button btnMultiChoiceList = (Button)findViewById(R.id.btnMultiChoiceList);  btnMultiChoiceList.setOnClickListener(this);  Button btnRemoveDialog = ( Button)findViewById(R.id.btnRemoveDialog);  btnRemoveDialog.setOnClickListener(this);   } public void onClick(View v) {  switch (v.getId()) {  case R.id.btnDeleteFile:   showDialog(DIALOG_DELLETE_FILM);   break;  case R.id.btnSimapleList:   showDialog(DIALOG_SIMPLE_LIST);   break;  case R.id.btnSingleChoiceList:   showDialog(DIALOG_SINGLE_CHOICE_LIST);   break;  case R.id.btnMultiChoiceList:   showDialog(DIALOG_MULTI_CHIOCE_LIST);   break;  case R.id.btnRemoveDialog:   removeDialog(DIALOG_DELLETE_FILM);   removeDialog(DIALOG_SIMPLE_LIST);   removeDialog(DIALOG_SINGLE_CHOICE_LIST);   removeDialog(DIALOG_MULTI_CHIOCE_LIST);   break;  } } protected Dialog onCreateDialog(int id) {  Log.d("dialog", String.valueOf(id));  switch (id) {  case DIALOG_DELLETE_FILM:   return new AlertDialog.Builder(this).setIcon(R.drawable.icon)     .setTitle("是否刪除檔案").setPositiveButton("確定",       new DialogInterface.OnClickListener() {        @Override        public void onClick(DialogInterface dialog,          int which) {         new AlertDialog.Builder(PhoneTest.this)           .setMessage("檔案已被刪除").create()           .show();        }       }).setNegativeButton("取消",       new DialogInterface.OnClickListener() {        @Override        public void onClick(DialogInterface dialog,          int which) {         new AlertDialog.Builder(PhoneTest.this)           .setMessage("檔案未被刪除").create()           .show();        }       }).create();  case DIALOG_SIMPLE_LIST:   return new AlertDialog.Builder(this).setTitle("選擇省份").setItems(     provinces, new DialogInterface.OnClickListener() {      @Override      public void onClick(DialogInterface dialog, int which) {       final AlertDialog ad = new AlertDialog.Builder(         PhoneTest.this).setMessage(         "你選擇了:" + which + ":" + provinces[which])         .show();       Handler handler = new Handler();       handler.postDelayed(new Runnable() {        @Override        public void run() {         ad.dismiss();        }       }, 5 * 1000);      }     }).create();  case DIALOG_SINGLE_CHOICE_LIST:   return new AlertDialog.Builder(this).setTitle("選擇省份")     .setSingleChoiceItems(provinces, 1, buttonOnClick)     .setPositiveButton("確定", buttonOnClick).setNegativeButton(       "取消", buttonOnClick).create();  case DIALOG_MULTI_CHIOCE_LIST:   AlertDialog ad = new AlertDialog.Builder(this).setIcon(     R.drawable.icon).setTitle("選擇省份").setMultiChoiceItems(     provinces,     new boolean[] { false, true, true, false, true, false },     new DialogInterface.OnMultiChoiceClickListener() {      @Override      public void onClick(DialogInterface dialog, int which,        boolean isChecked) {       // TODO Auto-generated method stub      }     }).setPositiveButton("確定",     new DialogInterface.OnClickListener() {      @Override      public void onClick(DialogInterface dialog, int which) {       int count = lv.getCount();       String s = "你選擇了:";       for (int i = 0; i < provinces.length; i++) {        if (lv.getCheckedItemPositions().get(i))         s += i + ":" + lv.getAdapter().getItem(i)           + "  ";       }       if (lv.getCheckedItemPositions().size() > 0) {        new AlertDialog.Builder(PhoneTest.this)          .setMessage(s).show();       } else {        new AlertDialog.Builder(PhoneTest.this)          .setMessage("您未選擇任何省份").show();       }      }     }).setNegativeButton("取消", null).create();   lv = ad.getListView();   return ad;  }  return null; } private class ButtonOnClick implements DialogInterface.OnClickListener {  private int index;  public ButtonOnClick(int index) {   this.index = index;  }  @Override  public void onClick(DialogInterface dialog, int whichButton) {   if (whichButton >= 0) {    index = whichButton;   } else {    if (whichButton == DialogInterface.BUTTON_POSITIVE) {     new AlertDialog.Builder(PhoneTest.this).setMessage(       "您已經選擇了: " + index + ":" + provinces[index]).show();    } else if (whichButton == DialogInterface.BUTTON_NEGATIVE) {     new AlertDialog.Builder(PhoneTest.this).setMessage(       "您什麼都未選擇.").show();    }   }  } } protected void OnPrepareDialog(int id, Dialog dialog) {  super.onPrepareDialog(id, dialog); } }以下是xml檔案<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:id="@+id/btnDeleteFile" android:layout_width="fill_parent"  android:layout_height="wrap_content" android:text="顯示確認要刪除檔案" /> <Button android:id="@+id/btnSimapleList" android:layout_width="fill_parent"  android:layout_height="wrap_content" android:text="顯示簡單列表對話方塊" /> <Button android:id="@+id/btnSingleChoiceList"  android:layout_width="fill_parent" android:layout_height="wrap_content"  android:text="顯示單選列表對話方塊" /> <Button android:id="@+id/btnMultiChoiceList"  android:layout_width="fill_parent" android:layout_height="wrap_content"  android:text="顯示多選列表複選框" />   <Button android:id="@+id/btnRemoveDialog" android:layout_width="fill_parent"  android:layout_height="wrap_content" android:text="把所有的對話方塊從activity中移除" /></LinearLayout>


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.