有時候我們需要在遊戲或應用中用一些符合我們樣式的提示框(alertdialog)
以下是我在開發一個小遊戲中總結出來的.希望對大家有用.
先上效果圖:
下面是用到的背景圖或按鈕的圖檔
經過查找資料和參考了一下例子後才知道,要實作這種效果很簡單.就是在設定alertdialog的contentview.
以下的代碼是寫在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() {
dlg.cancel();
}以下的是layout檔案,定義了對話框中的背景與按鈕.點選事件在activity中添加.
檔案名為 : shrew_exit_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<relativelayout
xmlns:android="http://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_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:background="@drawable/btn_ok" />
<!-- 取消按鈕 -->
android:layout_alignright="@+id/exitgamebackground"
android:layout_marginright="35dp"
android:id="@+id/btn_cancel"
android:background="@drawable/btn_cancel" />
</relativelayout>就這樣經過了以上幾步,就可以實作自定義alertdialog的效果了. 用同樣的思路可以實作其它更複雜的效果.