现在的位置: 首页 > 综合 > 正文

【自定义AlertDialog】退出提示框

2017年12月05日 ⁄ 综合 ⁄ 共 2177字 ⁄ 字号 评论关闭

 

有时候我们需要在游戏或应用中用一些符合我们样式的提示框(AlertDialog)

效果图:

下面是用到的背景图或按钮的图片

经过查找资料和参考了一下例子后才知道,要实现这种效果很简单.就是在设置alertDialog的contentView.以下的代码是写在Activity下的,代码如下:

  1. public boolean onKeyDown(int keyCode, KeyEvent event) {
  2. // 如果是返回键,直接返回到桌面
  3. if(keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME){
  4. showExitGameAlert();
  5. }

  6. return super.onKeyDown(keyCode, event);
  7. }
  8. private void showExitGameAlert() {
  9. final AlertDialog dlg = new AlertDialog.Builder(this).create();
  10. dlg.show();
  11. Window window = dlg.getWindow();
  12. // *** 主要就是在这里实现这种效果的.
  13. // 设置窗口的内容页面,shrew_exit_dialog.xml文件中定义view内容
  14. window.setContentView(R.layout.shrew_exit_dialog);
  15. // 为确认按钮添加事件,执行退出应用操作
  16. ImageButton ok = (ImageButton) window.findViewById(R.id.btn_ok);
  17. ok.setOnClickListener(new View.OnClickListener() {
  18. public void onClick(View v) {
  19. exitApp(); // 退出应用...
  20. }
  21. });

  22. // 关闭alert对话框架
  23. ImageButton cancel = (ImageButton) window.findViewById(R.id.btn_cancel);
  24. cancel.setOnClickListener(new View.OnClickListener() {
  25. public void onClick(View v) {
  26. dlg.cancel();
  27. }
  28. });
  29. }

以下的是layout文件,定义了对话框中的背景与按钮.点击事件在Activity中添加.
文件名为 : shrew_exit_dialog.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout 
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:layout_height="wrap_content" 
  5. android:layout_width="wrap_content">

  6. <!-- 退出游戏的背景图 -->
  7. <ImageView android:id="@+id/exitGameBackground"
  8. android:layout_centerInParent="true" 
  9. android:layout_height="wrap_content"
  10. android:layout_width="wrap_content" 
  11. android:src="@drawable/bg_exit_game" />

  12. <!-- 确认按钮 -->
  13. <ImageButton android:layout_alignBottom="@+id/exitGameBackground"
  14. android:layout_alignLeft="@+id/exitGameBackground"
  15. android:layout_marginBottom="30dp" 
  16. android:layout_marginLeft="35dp"
  17. android:id="@+id/btn_ok" 
  18. android:layout_height="wrap_content"
  19. android:layout_width="wrap_content" 
  20. android:background="@drawable/btn_ok" />

  21. <!-- 取消按钮 -->
  22. <ImageButton android:layout_alignBottom="@+id/exitGameBackground"
  23. android:layout_alignRight="@+id/exitGameBackground"
  24. android:layout_marginBottom="30dp" 
  25. android:layout_marginRight="35dp"
  26. android:id="@+id/btn_cancel" 
  27. android:layout_height="wrap_content"
  28. android:layout_width="wrap_content" 
  29. android:background="@drawable/btn_cancel" />
  30. </RelativeLayout>

就这样经过了以上几步,就可以实现自定义AlertDialog的效果了. 用同样的思路可以实现其它更复杂的效果.
原文出处:http://www.apkbus.com/android-27605-1-1.html

抱歉!评论已关闭.