Android 自定义AlertDialog退出对话框

转 https://blog.csdn.net/wkh11/article/details/53081634
在项目中很多时候会出现点击返回键出现提示对话框。


不多说了,先看效果图

 

直接上代码

layout布局的名字是close_program

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:andro />
        </LinearLayout>
    </RelativeLayout>
</RelativeLayout>


其中有个布局的背景是圆角矩形的设置

画圆角矩形的代码  tab_rectangle

<?xml version="1.0" encoding="utf-8"?>  
<shape xmlns:andro/>    
</shape> 

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();
        window.setContentView(R.layout.closeprogram);
        TextView tv = (TextView) window.findViewById(R.id.tv_no);
        tv.setText("你确定要退出吗");
        LinearLayout ok = (LinearLayout) window.findViewById(R.id.tv_ok);

        //确定按钮

        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                exit(); // 退出应用
            }
        });

        //取消按钮
        LinearLayout cancel = (LinearLayout) window.findViewById(R.id.tv_cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
    }

   //关闭程序

    private void exit() {
        super.finish();
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

假设想改变Dialog的大小能够这样写:

 

	AlertDialog dialog = getCustomDialog();
					dialog.show();
					
					//一定得在show完dialog后来set属性
					WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
					lp.width = AnimationTest.this.getResources().getDimensionPixelSize(R.dimen.dialog_width);
					lp.height = AnimationTest.this.getResources().getDimensionPixelSize(R.dimen.dialog_height);
					dialog.getWindow().setAttributes(lp);



相关文章:

  • 2021-11-15
  • 2021-04-10
  • 2022-12-23
  • 2021-05-03
  • 2021-06-24
  • 2022-12-23
  • 2021-07-09
猜你喜欢
  • 2022-12-23
  • 2022-01-01
  • 2022-02-27
  • 2021-06-17
相关资源
相似解决方案