編輯:關於 Android 程式設計
專案裡對話框的需求大致分三類:單純的確認提示、需要自訂版面的進度提示、以及需要輸入資料的表單。這三種對應三種不同的實作方式,本篇逐一整理。
最常見的場景。搭配 AsyncTask 使用時,按下「是」才真的執行刪除動作:
AlertDialog.Builder builder = new Builder(HomeActivity.this);
builder.setTitle("提示");
builder.setMessage("是否刪除信息?");
builder.setPositiveButton("是", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
if (mRejectLeaveInfoDao == null) {
mRejectLeaveInfoDao = new RejectLeaveInfosDao(HomeActivity.this);
} else {
mRejectLeaveInfoDao.deleteLeaveInfo(tmpInfoReject);
}
fillDataReject();
return null;
}
}.execute();
}
});
builder.setNegativeButton("否", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
注意 doInBackground 裡才是真正做資料庫動作的環境;若把刪除寫在 onClick 裡直接執行,資料量一大就會造成 ANR。
掃描、下載這類需要顯示進度又不想讓使用者亂按的場合,直接用 Dialog 換上自訂版面,並用 setCancelable(false) 禁掉返回鍵關閉:
new AsyncTask<Void, Object, Void>() {
List<VirusApp> apps = new ArrayList<VirusApp>();
String desc = null;
Dialog dialog = new Dialog(KillVirusActivity.this);
View viewKilling = View.inflate(KillVirusActivity.this, R.layout.killing_dialog, null);
@Override
protected void onPreExecute() {
mKillVirusResult.setText("正在掃描中,請稍等...");
dialog.setCancelable(false);
dialog.setContentView(viewKilling);
dialog.show();
}
// ...
};
對應的版面檔很簡單,一個 ProgressBar 加一行說明文字:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="病毒掃描中..."
android:textSize="15sp" />
</LinearLayout>
當對話框裡要放好幾個 EditText、需要鍵盤輸入並驗證時,Dialog 的版面會很難安排。更靈活的做法是「把 Activity 做成對話框的樣子」:去掉標題列與狀態列,讓它半透明地浮在上層。
public class AddKeyWordsInfosDailogActivity extends Activity {
protected static final int ADD_KEY_INFO_SCUCESS = 100;
private EditText et_key_words_input; // 輸入關鍵字
private EditText et_key_words_decribe;
private Button mSure; // 確定
private Button mCancel; // 取消
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // 去除 title
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN); // 去掉狀態列
setContentView(R.layout.add_keyword_info_activity);
init();
setListener();
}
private void setListener() {
mSure.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
KeyWordInfoDao dao = new KeyWordInfoDao(getApplicationContext());
if (et_key_words_input.getText().toString().trim().length() == 0) {
Toast.makeText(AddKeyWordsInfosDailogActivity.this, "請輸入關鍵字或者取消!", 300).show();
return;
}
if (et_key_words_decribe.getText().toString().trim().length() == 0) {
Toast.makeText(AddKeyWordsInfosDailogActivity.this, "請輸入關鍵字描述內容或者取消!", 300).show();
return;
}
KeyWordInfo info = new KeyWordInfo();
info.setKey_word_info(et_key_words_input.getText().toString().trim());
info.setKey_word_decribe(et_key_words_decribe.getText().toString().trim());
dao.addKeyWordInfos(info);
info = null;
setResult(ADD_KEY_INFO_SCUCESS, getIntent());
AddKeyWordsInfosDailogActivity.this.finish();
}
});
mCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AddKeyWordsInfosDailogActivity.this.finish();
}
});
}
private void init() {
et_key_words_input = (EditText) findViewById(R.id.et_key_words_input);
et_key_words_decribe = (EditText) findViewById(R.id.et_key_words_decribe);
mSure = (Button) findViewById(R.id.btn_sure);
mCancel = (Button) findViewById(R.id.btn_cancel);
}
}
版面檔:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="添加關鍵字"
android:gravity="center" />
<TextView
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="請輸入需要攔截的關鍵字(最多16個字,允許漢字,字母,數字)"
android:gravity="center" />
<EditText
android:id="@+id/et_key_words_input"
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="55dp" />
<EditText
android:id="@+id/et_key_words_decribe"
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="55dp"
android:hint="輸入描述內容" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btn_cancel"
android:layout_width="160dp"
android:layout_height="55dp"
android:text="取消"
android:layout_alignParentLeft="true"
android:background="@drawable/sure_cancel_selector" />
<Button
android:id="@+id/btn_sure"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignParentRight="true"
android:layout_toRightOf="@+id/btn_cancel"
android:text="確定"
android:background="@drawable/sure_cancel_selector" />
</RelativeLayout>
</LinearLayout>
效果圖:

三者的取捨其實很清楚:AlertDialog 用最少程式碼換到系統標準外觀,適合純文字確認;Dialog 適合自訂版面但不便輸入;Activity 樣式視窗自由度最高,代價是要自己處理半透明背景(在 theme 裡設 android:windowIsTranslucent 與 windowBackground)以及回傳結果的 setResult 約定。
無論哪一種,記得對話框必須持有一個有效的 Activity Context,且要在 Activity 進入背景前妥善 dismiss,否則很容易拿到 WindowLeaked 的錯誤。若使用 Fragment,優先考慮 DialogFragment,它能跟著 Fragment 生命週期一起被管理,省去這些手動處理。
Android ListView 分頁加載數據實戰:滑到底自動載入更多
熟悉 Android 的朋友都知道,不管是微博客戶端還是新聞客戶端,都離不開列表元件。可以說 ListView 是 Android 在資料展現方面最重要的元件之一。今天我
21 天學會 Android 開發:MediaPlayer 影音播放實作
本文來談 MediaPlayer。它可以播放音訊與影片,是 Android 多媒體播放的核心類別。 如果只是要播影片,VideoView 更簡單易用;但客製化程度不如 M
Android 正方形顯示圖片並適配手機:GridView 圖標牆實作解析
問題背景 在應用牆中,需要用 GridView 顯示圖標與名稱。若只設定四列,不同分辨率的手機會出現圖片大小不一致與拉伸問題。 設定 GridView 列寬 可將 n
Android 圖片疊加效果的兩種實現方案詳解
圖片疊加是開發中經常冒出的需求,比如給列表圖片加個播放按鈕、給頭像鑲個邊框,或者做多層素材合成。本文整理了兩種在 Android 中實現圖片疊加的經典方案,並附上完整的