安卓dialog彈出dialog,Android Dialog用法

 2023-12-06 阅读 20 评论 0

摘要:摘要: 創建對話框 一個對話框一般是一個出現在當前Activity之上的一個小窗口. 處于下面的Activity失去焦點, 對話框接受所有的用戶交互. 對話框一般用于提示信息和與當前應用程序直接相關的小功能.Android API 支持下列類型 ... 創建對話框  一個對話框一般是一個出現在當前

摘要: 創建對話框 一個對話框一般是一個出現在當前Activity之上的一個小窗口. 處于下面的Activity失去焦點, 對話框接受所有的用戶交互. 對話框一般用于提示信息和與當前應用程序直接相關的小功能.Android API 支持下列類型 ...

創建對話框
  一個對話框一般是一個出現在當前Activity之上的一個小窗口. 處于下面的Activity失去焦點, 對話框接受所有的用戶交互. 對話框一般用于提示信息和與當前應用程序直接相關的小功能.
  Android API 支持下列類型的對話框對象:
  警告對話框 AlertDialog:? 一個可以有0到3個按鈕, 一個單選框或復選框的列表的對話框. 警告對話框可以創建大多數的交互界面, 是推薦的類型.
  進度對話框 ProgressDialog:? 顯示一個進度環或者一個進度條. 由于它是AlertDialog的擴展, 所以它也支持按鈕.
  日期選擇對話框 DatePickerDialog:? 讓用戶選擇一個日期.
  時間選擇對話框 TimePickerDialog:? 讓用戶選擇一個時間.
  如果你希望自定義你的對話框, 可以擴展Dialog類.
  Showing a Dialog 顯示對話框
  一個對話框總是被創建和顯示為一個Activity的一部分. 你應該在Activity的onCreateDialog(int)中創建對話框. 當你使用這個回調函數時,Android系統自動管理每個對話框的狀態并將它們和Activity連接, 將Activity變為對話框的"所有者". 這樣,每個對話框從Activity繼承一些屬性. 例如,當一個對話框打開時, MENU鍵會顯示Activity的菜單, 音量鍵會調整Activity當前使用的音頻流的音量.
  注意: 如果你希望在onCreateDialog()方法之外創建對話框, 它將不會依附在Activity上. 你可以使用setOwnerActivity(Activity)來將它依附在Activity上.
  當你希望顯示一個對話框時, 調用showDialog(int)并將對話框的id傳給它.
  當一個對話框第一次被請求時,Android調用onCreateDialog(int). 這里是你初始化對話框的地方. 這個回調函數傳入的id和showDialog(int)相同. 創建對話框之后,將返回被創建的對象.
  在對話框被顯示之前,Android還會調用onPrepareDialog(int, Dialog). 如果你希望每次顯示對話框時有動態更改的內容, 那么就改寫這個函數. 該函數在每次一個對話框打開時都調用. 如果你不定義該函數,則對話框每次打開都是一樣的. 該函數也會傳入對話框的id以及你在onCreateDialog()中創建的Dialog對象.
  最好的定義onCreateDialog(int) 和onPrepareDialog(int, Dialog) 的方法就是使用一個switch語句來檢查傳入的id. 每個case創建相應的對話框. 例如, 一個游戲使用兩個對話框: 一個來指示游戲暫停,另一個指示游戲結束. 首先, 為它們定義ID:static final int DIALOG_PAUSED_ID = 0;
static final int DIALOG_GAMEOVER_ID = 1;?
然后, 在onCreateDialog(int)中加入一個switch語句:
復制代碼
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;
} 
復制代碼

安卓dialog彈出dialog。注意: 在這個例子中, case語句為空因為定義Dialog的程序在后面會有介紹.
  在需要顯示對話框是, 調用showDialog(int), 傳入對話框的id:
  showDialog(DIALOG_PAUSED_ID);Dismissing a Dialog 解除對話框
  當你準備關閉對話框時, 你可以使用dismiss()函數. 如果需要的話, 你也可以從Activity調用dismissDialog(int), 二者效果是一樣的.
  如果你使用onCreateDialog(int)來管理你的對話框的狀態, 那么每次你的對話框被解除時, 該對話框對象的狀態會被Activity保存. 如果你決定你不再需要這個對象或者需要清除對話框的狀態, 那么你應該調用 removeDialog(int). 這將把所有該對象的內部引用移除, 如果該對話框在顯示的話將被解除.
  Using dismiss listeners 使用解除監聽器
  如果你希望在對話框解除時運行某些程序, 那么你應該給對話框附加一個解除監聽器.
  首先定義DialogInterface.OnDismissListener接口. 這個接口只有一個方法, onDismiss(DialogInterface), 該方法將在對話框解除時被調用.
  然后將你的OnDismissListener實現傳給setOnDismissListener().
  然而,注意對話框也可以被"取消". 這是一個特殊的情形, 它意味著對話框被用戶顯式的取消掉. 這將在用戶按下"back"鍵時, 或者對話框顯式的調用cancel()(按下對話框的cancel按鈕)時發生. 當一個對話框被取消時, OnDismissListener將仍然被通知, 但如果你希望在對話框被顯示取消(而不是正常解除)時被通知, 則你應該使用setOnCancelListener()注冊一個DialogInterface.OnCancelListener.
  Creating an AlertDialog 創建警告對話框
  An AlertDialog is an extension of the Dialog class. It is capable of constructing most dialog user interfaces and is the suggested dialog type. You should use it for dialogs that use any of the following features:
  一個警告對話框是對話框的一個擴展. 它能夠創建大多數對話框用戶界面并且是推薦的對話框類新星. 對于需要下列任何特性的對話框,你都應該使用它:
  一個標題
  一條文字消息
  1個-3個按鈕
  一個可選擇的列表(單選框或者復選框)
  要創建一個AlertDialog, 使用AlertDialog.Builder子類. 使用AlertDialog.Builder(Context)來得到一個Builder, 然后使用該類的公有方法來定義AlertDialog的屬性. 設定好以后, 使用create()方法來獲得AlertDialog對象.
  下面的主題展示了如何為AlertDialog定義不同的屬性, 使用AlertDialog.Builder類. 如果你使用這些示例代碼, 你可以在onCreateDialog()中返回最后的Dialog對象來獲得圖片中對話框的效果.
  Adding buttons 增加按鈕

要創建一個如圖所示的窗口, 使用set...Button()方法:

復制代碼
AlertDialog.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();}}).show();
AlertDialog alert = builder.create();
復制代碼
首先,使用setMessage(CharSequence)為對話框增加一條消息。 然后, 開始連續調用方法, 使用setCancelable(boolean)將對話框設為不可取消(不能使用back鍵來取消)。對每一個按鈕,使用set...Button()方法,該方法接受按鈕名稱和一個DialogInterface.OnClickListener,該監聽器定義了當用戶選擇該按鈕時應做的動作。
  注意:對每種按鈕類型,只能為AlertDialog創建一個。也就是說,一個AlertDialog不能有兩個以上的"positive"按鈕。這使得可能的按鈕數量最多為三個:肯定、否定、中性。這些名字和實際功能沒有聯系,但是將幫助你記憶它們各做什么事情。
Adding a list 增加列表

要創建一個具有可選項的AlertDialog,使用setItems()方法

復制代碼
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();
復制代碼
首先增加一個標題。然后使用setItems()增加一個可選列表,該列表接受一個選項名稱的列表和一個DialogInterface.OnClickListener, 后者定義了選項對應的響應。

Adding checkboxes and radio buttons 增加單選框和復選框

要創建一個帶有多選列表或者單選列表的對話框, 使用setMultiChoiceItems()和setSingleChoiceItems()方法。如果你在onCreateDialog()中創建可選擇列表, Android會自動管理列表的狀態. 只要activity仍然活躍, 那么對話框就會記住剛才選中的選項,但當用戶退出activity時,該選擇丟失。
  注意: 要在你的acitivity離開和暫停時保存選擇, 你必須在activity的聲明周期中正確的保存和恢復設置。為了永久性保存選擇,你必須使用數據存儲技術中的一種。
  要創建一個具有單選列表的AlertDialog,只需將一個例子中的setItems()換成 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();
復制代碼
第二個參數是默認被選中的選項位置,使用“-1”來表示默認情況下不選中任何選項。

Creating a ProgressDialog 創建進度對話框

一個ProgressDialog(進度對話框)是AlertDialog的擴展。它可以顯示一個進度的動畫——進度環或者進度條。這個對話框也可以提供按鈕,例如取消一個下載等。
  打開一個進度對話框很簡單,只需要調用 ProgressDialog.show()即可。例如,上圖的對話框可以不通過onCreateDialog(int),而直接顯示:
  ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "",
  "Loading. Please wait...", true);
  第一個參數是應用程序上下文。第二個為對話框的標題(這里為空),第三個為對話框內容, 最后一個為該進度是否為不可確定的(這只跟進度條的創建有關,見下一節)。
  進度對話框的默認樣式為一個旋轉的環。如果你希望顯示進度值,請看下一節。
  Showing a progress bar 顯示進度條
  使用一個動畫進度條來顯示進度:
  使用 ProgressDialog(Context)構造函數來初始化一個ProgressDialog對象。
  將進度樣式設置為"STYLE_HORIZONTAL",使用setProgressStyle(int)方法。并且設置其它屬性,例如內容等。
  在需要顯示時調用show()或者從onCreateDialog(int)回調函數中返回該ProgressDialog。
  你可以使用 setProgress(int)或者incrementProgressBy(int)來增加顯示的進度。
  例如,你的設置可能像這樣:ProgressDialog progressDialog;
progressDialog = new ProgressDialog(mContext);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
  設置很簡單。大部分創建進度對話框需要的代碼是在更新它的進程中。你可能需要在一個新的線程中更新它,并使用Handler來將進度報告給Activity。如果你不熟悉使用Handler和另外的線程,請看下列例子,該例子使用了一個新的線程來更新進度。
  Example ProgressDialog with a second thread 例--使用一個線程來顯示進度對話框
  這個例子使用一個線程來跟蹤一個進程的進度(其實為從1數到100)。每當進度更新時,該線程通過Handler給主activity發送一個消息。主Activity更新ProgressDialog.package com.example.progressdialog;

復制代碼
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class NotificationTest extends Activity {static final int PROGRESS_DIALOG = 0;Button button;ProgressThread progressThread;ProgressDialog progressDialog;/** Called when the activity is first created. */public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main); // Setup the button that starts the progress dialogbutton = (Button) findViewById(R.id.progressDialog);button.setOnClickListener(new OnClickListener(){public void onClick(View v) {showDialog(PROGRESS_DIALOG);}});}protected Dialog onCreateDialog(int id) {switch(id) {case PROGRESS_DIALOG:progressDialog = new ProgressDialog(NotificationTest.this);progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);progressDialog.setMessage("Loading...");progressThread = new ProgressThread(handler);progressThread.start();return progressDialog;default:return null;}} // Define the Handler that receives messages from the thread and update the progressfinal Handler handler = new Handler() {public void handleMessage(Message msg) {int total = msg.getData().getInt("total");progressDialog.setProgress(total);if (total >= 100){dismissDialog(PROGRESS_DIALOG);progressThread.setState(ProgressThread.STATE_DONE);}}}; /** Nested class that performs progress calculations (counting) */private class ProgressThread extends Thread {Handler mHandler;final static int STATE_DONE = 0;final static int STATE_RUNNING = 1;int mState;int total;ProgressThread(Handler h) {mHandler = h;}public void run() {mState = STATE_RUNNING;   total = 0;while (mState == STATE_RUNNING) {try {Thread.sleep(100);} catch (InterruptedException e) {Log.e("ERROR", "Thread Interrupted");}Message msg = mHandler.obtainMessage();Bundle b = new Bundle();b.putInt("total", total);msg.setData(b);mHandler.sendMessage(msg);total++;}}/* sets the current state for the thread,* used to stop the thread */public void setState(int state) {mState = state;}}
}
復制代碼

Creating a Custom Dialog 創建自定義對話框

如果你想自定義一個對話框,你可以使用布局元素來創造你的對話框的布局。定義好布局后,將根View對象或者布局資源ID傳給setContentView(View).
例如,創建如圖所示的對話框:
創建一個xml布局custom_dialog.xml:

復制代碼
http://schemas.android.com/apk/res/android"android:id="@+id/layout_root"android:orientation="horizontal"android:layout_width="fill_parent"android:layout_height="fill_parent"android:padding="10dp">android:layout_width="wrap_content"android:layout_height="fill_parent"android:layout_marginRight="10dp"/>android:layout_width="wrap_content"android:layout_height="fill_parent"android:textColor="#FFF"/>
復制代碼

該xml定義了一個LinearLayout中的一個ImageView 和一個TextView。
將以上布局設為對話框的content view,并且定義ImageView 和 TextView的內容:

復制代碼
Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext); 
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.android);
復制代碼

在初始化Dialog之后,使用setContentView(int),將布局資源id傳給它。現在Dialog有一個定義好的布局,你可以使用findViewById(int)來找到該元素的id并修改它的內容。
  使用前面所講的方法顯示對話框。
  一個使用Dialog類建立的對話框必須有一個標題。如果你不調用setTitle(),那么標題區域會保留空白。如果你不希望有一個標題,那么你應該使用AlertDialog類來創建自定義對話框。然而,由于一個AlertDialog使用AlertDialog.Builder類來建立最方便,所以你沒有方法使用setContentView(int),而是只能使用setView(View)。該方法接受一個View對象,所以你需要從xml中展開你的根View。
  要展開一個xml布局,使用 getLayoutInflater() (或 getSystemService())取得LayoutInflater,然后調用inflate(int, ViewGroup),第一個參數為布局id,而第二個參數為根view的id。現在,你可以使用展開后的布局來找到View對象并定義ImageView和TextView元素的內容。然后實例化AlertDialog.Builder并使用setView(View)來為對話框設置展開后的布局。例如:

復制代碼
AlertDialog.Builder builder;
AlertDialog alertDialog; 
Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog,(ViewGroup) findViewById(R.id.layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.android);
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();
復制代碼

使用AlertDialog來自定義對話框,可以利用其內置特性例如按鈕、選擇列表、標題、圖標等。

?

轉載于:https://www.cnblogs.com/wangxiuheng/p/4483810.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/192508.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息