Android使用自定义AlertDialog

Android使用自定义AlertDialog




以下的代码是写在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中添加.

http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content">


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

猜你喜欢

转载自duohuoteng.iteye.com/blog/1756286