当前位置: 移动技术网 > 移动技术>移动开发>Android > Android编程之自定义AlertDialog(退出提示框)用法实例

Android编程之自定义AlertDialog(退出提示框)用法实例

2019年07月24日  | 移动技术网移动技术  | 我要评论

本文实例讲述了android编程自定义alertdialog(退出提示框)用法,分享给大家供大家参考,具体如下:

有时候我们需要在游戏或应用中用一些符合我们样式的提示框(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() {
  public void onclick(view v) {
  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_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>

就这样经过了以上几步,就可以实现自定义alertdialog的效果了. 用同样的思路可以实现其它更复杂的效果.

希望本文所述对大家android程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网