android监听返回按钮事件

用户在点击手机的返回按钮时,默认是推出当前的activty,但是有时用户不小心按到返回,所以需要给用户一个提示,这就需要重写onkeydown事件,实现的效果如下:
标签: Android SDK

代码片段(2)

[图片] 截图

android监听返回按钮事件_第1张图片

[代码] [Java]代码

01 @Override 
02     public void onCreate(Bundle savedInstanceState) { 
03         super.onCreate(savedInstanceState); 
04         setContentView(R.layout.main); 
05     
06     protected void dialog() { 
07         AlertDialog.Builder builder = new Builder(HanderTestActivty.this); 
08         builder.setMessage("确定要退出吗?"); 
09         builder.setTitle("提示"); 
10         builder.setPositiveButton("确认"
11                 new android.content.DialogInterface.OnClickListener() { 
12                     @Override 
13                     public void onClick(DialogInterface dialog, int which) { 
14                         dialog.dismiss(); 
15                         HanderTestActivty.this.finish(); 
16                     
17                 }); 
18         builder.setNegativeButton("取消"
19                 new android.content.DialogInterface.OnClickListener() { 
20                     @Override 
21                     public void onClick(DialogInterface dialog, int which) { 
22                         dialog.dismiss(); 
23                     
24                 }); 
25         builder.create().show(); 
26     
27     @Override 
28     public boolean onKeyDown(int keyCode, KeyEvent event) { 
29         if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { 
30             dialog(); 
31             return false
32         
33         return false
34     }

你可能感兴趣的:(java,android,dialog,手机)