編輯:關於 Android 程式設計
Dialog(對話框)是 Android 中與使用者互動的重要元件。本文整理了多種常見的 Dialog 實作方式,涵蓋自訂樣式、退出確認、輸入表單、進度提示與各類選擇清單等情境。
透過自訂版面搭配旋轉動畫,可做出類似進度對話框的效果。版面配置如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/dialog_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/loading_bg"
android:gravity="center"
android:minHeight="60dp"
android:minWidth="180dp"
android:orientation="vertical"
android:padding="10dp">
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/loading" />
<TextView
android:id="@+id/tipTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dip"
android:text="數據加載中……"
android:textColor="@android:color/black"
android:textSize="18dip" />
</LinearLayout>
自訂的樣式:
<!-- 自定義 loading dialog 樣式 -->
<style name="loading_dialog" parent="android:style/Theme.Dialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@drawable/loading_bg</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">@null</item>
</style>
自訂的旋轉動畫:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<!-- 自定義旋轉的動畫 -->
<rotate
android:duration="2000"
android:fromDegrees="0"
android:interpolator="@android:anim/linear_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="-1"
android:repeatMode="restart"
android:startOffset="-1"
android:toDegrees="360" />
</set>
實作方法:
LayoutInflater inflater = LayoutInflater.from(this);
View v = inflater.inflate(R.layout.loading_dialog, null); // 得到加載 view
LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view); // 加載布局
ImageView spaceshipImage = (ImageView) v.findViewById(R.id.img);
TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView); // 提示文字
// 加載動畫
Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(this, R.drawable.loading_animation);
spaceshipImage.startAnimation(hyperspaceJumpAnimation);
tipTextView.setText("dddd"); // 設置加載信息
Dialog loadingDialog = new Dialog(this, R.style.loading_dialog); // 創建自定義樣式 dialog
loadingDialog.setCancelable(true);
loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT)); // 設置布局
loadingDialog.show();
// loadingDialog.cancel(); // 取消對話框
透過 CustomDialog.Builder 封裝,可靈活設定標題、訊息、正反兩顆按鈕及其點擊事件。以下為 Builder 的核心結構:
public class CustomDialog extends Dialog {
public CustomDialog(Context context, int theme) {
super(context, theme);
}
public CustomDialog(Context context) {
super(context);
}
public static class Builder {
private Context context;
private String title;
private String message;
private String positiveButtonText;
private String negativeButtonText;
private View contentView;
private DialogInterface.OnClickListener positiveButtonClickListener,
negativeButtonClickListener;
public Builder(Context context) {
this.context = context;
}
public Builder setMessage(String message) {
this.message = message;
return this;
}
public Builder setTitle(String title) {
this.title = title;
return this;
}
public Builder setPositiveButton(String positiveButtonText,
DialogInterface.OnClickListener listener) {
this.positiveButtonText = positiveButtonText;
this.positiveButtonClickListener = listener;
return this;
}
public Builder setNegativeButton(String negativeButtonText,
DialogInterface.OnClickListener listener) {
this.negativeButtonText = negativeButtonText;
this.negativeButtonClickListener = listener;
return this;
}
public CustomDialog create() {
// 載入自訂版面,設定標題、按鈕與訊息後回傳 dialog
// (此處省略版面綁定細節)
return null;
}
}
}
在 Activity 中使用:
CustomDialog.Builder customBuilder = new CustomDialog.Builder(Tab_check5.this);
customBuilder.setTitle("提示").setMessage(R.string.exitapp)
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(Tab_check5.this, "你點擊了取消按鈕", 1).show();
dialog.dismiss();
}
})
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(Tab_check5.this, "你點擊了確定按鈕", 1).show();
// 退出 app 的操作
SysApplication.getInstance().exit();
dialog.dismiss();
}
});
dialog = customBuilder.create();
dialog.show();
透過 setView() 將自訂的輸入版面掛載到 AlertDialog 上,即可收集使用者輸入:
LayoutInflater layoutInflater = LayoutInflater.from(AndroidDemoActivity.this);
final View dialogview = layoutInflater.inflate(R.layout.dialog, null);
new AlertDialog.Builder(AndroidDemoActivity.this)
.setIcon(R.drawable.wawa)
.setTitle("親、給個評價呗!!")
.setView(dialogview)
.setPositiveButton("提交評價", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
EditText pingjia = (EditText) dialogview.findViewById(R.id.pingjia);
EditText qq = (EditText) dialogview.findViewById(R.id.qq);
String pingjiacontext = pingjia.getText().toString();
String qqcontext = qq.getText().toString();
// 在這裡處理使用者輸入的內容
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(AndroidDemoActivity.this, "親、你點擊了取消按鈕!!", Toast.LENGTH_LONG).show();
}
})
.create()
.show();
直接使用 setView() 掛上一個 TextView,或透過 setMessage() 顯示一段提示文字:
TextView msg = new TextView(this);
msg.setText("Hello everyone, Welcome to android world!");
new AlertDialog.Builder(AndroidDemoActivity.this)
.setIcon(R.drawable.wawa)
.setTitle("跟著王傑學android")
.setView(msg)
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// 確定事件
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 取消事件
}
}).create().show();
透過 onCreateDialog() 建立水平進度樣式,並以 Handler 搭配背景執行緒推進進度:
@Override
public Dialog onCreateDialog(int id) {
switch (id) {
case 0:
progressDialog = new ProgressDialog(this);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setTitle("進度對話框");
progressDialog.setCancelable(false); // 不能用返回鍵關閉
break;
}
return progressDialog;
}
@Override
public void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
switch (id) {
case 0:
progressDialog.incrementProgressBy(-progressDialog.getProgress());
new Thread() {
public void run() {
while (true) {
handler.sendEmptyMessage(0);
if (progressDialog.getProgress() >= 100) {
break;
}
try {
Thread.sleep(30);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
break;
}
}
透過 setItems() 顯示一組選項,使用者在點選後會觸發對應的監聽器:
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
Builder builder = new AlertDialog.Builder(this);
switch (id) {
case 0:
builder.setIcon(R.drawable.wawa)
.setTitle("列表對話框")
.setItems(R.array.colledge, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
editText.setText("你選擇的是:"
+ getResources().getStringArray(R.array.colledge)[which]);
}
})
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(AndroidDemoActivity.this, "你點擊了確定按鈕!!", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
editText.setText("你取消了選擇");
}
}).create();
dialog = builder.create();
break;
}
return dialog;
}
使用 setSingleChoiceItems() 呈現單選清單,第二個參數為預設選取的索引:
builder.setIcon(R.drawable.wawa)
.setTitle("單選按鈕對話框")
.setSingleChoiceItems(R.array.colledge, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
editText.setText("你選擇的是:"
+ getResources().getStringArray(R.array.colledge)[which]);
}
})
.setPositiveButton("確定", /* listener */ null)
.setNegativeButton("取消", /* listener */ null).create();
使用 setMultiChoiceItems() 呈現可複選的清單,透過一個 boolean 陣列記錄勾選狀態:
boolean[] mulFlags = new boolean[] { true, false, false, false };
builder.setIcon(R.drawable.wawa)
.setTitle("多選按鈕對話框")
.setMultiChoiceItems(R.array.colledge, mulFlags,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
mulFlags[which] = isChecked;
String result = "你選擇的是:";
for (int i = 0; i < mulFlags.length; i++) {
if (mulFlags[i]) {
result = result + items[i] + " ";
}
}
editText.setText(result.substring(0, result.length() - 1));
}
})
.setPositiveButton("確定", /* listener */ null)
.setNegativeButton("取消", /* listener */ null).create();
以上就是 Android 中 Dialog 的常見用法。從自訂樣式、退出確認、輸入表單,到進度提示與各類選擇清單,掌握這些模式後就能應付絕大多數的互動情境。需要留意的是,ProgressDialog 在 API 26 起已被標記為不建議使用,新專案建議改用 ProgressBar 搭配自訂 Dialog 或 DialogFragment 來實作。
Android Handler 消息機制全面詳解
先看效果演示: 顧名思義,一個 Handler 允許你發送和處理消息(Message)以及與某個線程消息隊列關聯的 Runnable 對象。每個 Handler 實例
自定義 ListView 實現 iOS 風格側滑子菜單
老規矩,先看效果,完整 DEMO 在文末。 當年剛接觸 Android 時看到這個效果只有膜拜的份,現在自己動手把它做出來,也算是圓了當年的一個念頭。 一、思路拆解
Android Fragment 生命週期詳解
Fragment 的生命週期 每個 Fragment 都有自己的一套生命週期回調方法,並自行處理用戶輸入事件。對應的生命週期可參考下圖: 創建 Fragment 要創建
用方向傳感器實現 Android 電子指南針
電子指南針的原理並不複雜:讀取設備的方向傳感器拿到方位角,再驅動一張指針圖片旋轉即可。本文用不到五十行代碼完成這個效果。 一、布局文件 界面只有一個居中的 Image