本文實(shí)例講述了android編程自定義alertdialog(退出提示框)用法,分享給大家供大家參考,具體如下:
有時(shí)候我們需要在游戲或應(yīng)用中用一些符合我們樣式的提示框(alertdialog)
以下是我在開發(fā)一個(gè)小游戲中總結(jié)出來(lái)的.希望對(duì)大家有用.
先上效果圖:
下面是用到的背景圖或按鈕的圖片
經(jīng)過(guò)查找資料和參考了一下例子后才知道,要實(shí)現(xiàn)這種效果很簡(jiǎn)單.就是在設(shè)置alertdialog的contentview.
以下的代碼是寫在activity下的,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
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(); // *** 主要就是在這里實(shí)現(xiàn)這種效果的. // 設(shè)置窗口的內(nèi)容頁(yè)面,shrew_exit_dialog.xml文件中定義view內(nèi)容 window.setcontentview(r.layout.shrew_exit_dialog); // 為確認(rèn)按鈕添加事件,執(zhí)行退出應(yīng)用操作 imagebutton ok = (imagebutton) window.findviewbyid(r.id.btn_ok); ok.setonclicklistener( new view.onclicklistener() { public void onclick(view v) { exitapp(); // 退出應(yīng)用... } }); // 關(guān)閉alert對(duì)話框架 imagebutton cancel = (imagebutton) window.findviewbyid(r.id.btn_cancel); cancel.setonclicklistener( new view.onclicklistener() { public void onclick(view v) { dlg.cancel(); } }); } |
以下的是layout文件,定義了對(duì)話框中的背景與按鈕.點(diǎn)擊事件在activity中添加.
文件名為 : shrew_exit_dialog.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<?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_height= "wrap_content" android:layout_width= "wrap_content" android:src= "@drawable/bg_exit_game" /> <!-- 確認(rèn)按鈕 --> <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> |
就這樣經(jīng)過(guò)了以上幾步,就可以實(shí)現(xiàn)自定義alertdialog的效果了. 用同樣的思路可以實(shí)現(xiàn)其它更復(fù)雜的效果.
希望本文所述對(duì)大家android程序設(shè)計(jì)有所幫助。