Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自訂 AlertDialog 做遊戲風格退出提示框

編輯:關於 Android 程式設計

做遊戲或風格化應用時,系統預設的 AlertDialog 常常完全不搭。好在客製化非常簡單——關鍵就是把自訂的 layout 塞進對話框的內容區。

先看成果:

做法:換掉 contentView

流程是這樣的:建立 AlertDialog 並 show 之後,透過 getWindow().setContentView() 指定自己的 layout,再用 window.findViewById() 取得裡面的按鈕掛上事件。以下程式碼寫在 Activity 中:

 public boolean onKeyDown(int keyCode, KeyEvent event) { // 如果是返回鍵,直接返回到桌面 if(keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME){ showExitGameAlert(); } return super.onKeyDown(keyCode, event); } private void showExitGameAlert() { final AlertDialog dlg = new AlertDialog.Builder(this).create(); dlg.show(); Window window = dlg.getWindow(); // *** 主要就是在這裡實現這種效果的. // 設置窗口的內容頁面,shrew_exit_dialog.xml文件中定義view內容 window.setContentView(R.layout.shrew_exit_dialog); // 為確認按鈕添加事件,執行退出應用操作 ImageButton ok = (ImageButton) window.findViewById(R.id.btn_ok); ok.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { exitApp(); // 退出應用... } }); // 關閉alert對話框架 ImageButton cancel = (ImageButton) window.findViewById(R.id.btn_cancel); cancel.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { dlg.cancel(); } }); } 

這裡有個順序上的重點:show() 必須在 setContentView() 之前呼叫,否則 window 尚未建立,會拿到 null。另外,改用自訂 layout 之後,findViewById 一定要從 window 而非 dlg 去找,這也是常見的失誤點。

自訂 layout

佈局檔 shrew_exit_dialog.xml 以一張背景圖為基準,用相對定位把確認與取消按鈕擺在圖上:

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:Android="https://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:layout_width="wrap_content"> <!-- 退出游戲的背景圖 --> <ImageView android:id="@+id/exitGameBackground" android:layout_centerInParent="true" android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/bg_exit_game" /> <!-- 確認按鈕 --> <ImageButton android:layout_alignBottom="@+id/exitGameBackground" android:layout_alignLeft="@+id/exitGameBackground" android:layout_marginBottom="30dp" android:layout_marginLeft="35dp" android:id="@+id/btn_ok" android:layout_height="wrap_content" android:layout_width="wrap_content" android:background="@drawable/btn_ok" /> <!-- 取消按鈕 --> <ImageButton android:layout_alignBottom="@+id/exitGameBackground" android:layout_alignRight="@+id/exitGameBackground" android:layout_marginBottom="30dp" android:layout_marginRight="35dp" android:id="@+id/btn_cancel" android:layout_height="wrap_content" android:layout_width="wrap_content" android:background="@drawable/btn_cancel" /> </RelativeLayout> 

layout_alignBottom 搭配 layout_alignLeft/Right 讓按鈕以背景圖為定位基準,再用 margin 微調間距。若背景圖在不同解析度下比例會跑掉,改用 android:scaleType 或改用 FrameLayout 分層會更穩。

延伸應用

同一個思路可以用在任何需要客製外觀的對話框:把 window.setContentView() 換成你的 layout,裡面放 EditText 就是輸入框,放自訂 View 就是特殊提示。若想連背景也換掉,可以再加上 window.setBackgroundDrawable(...),並用 setGravity 控制對話框在畫面上的位置。

掌握這幾個 API,系統對話框就不再受限於預設樣式了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved