android 自定义按钮实现 home键 和返回键

来源:互联网 发布:手机淘宝在哪里秒杀 编辑:程序博客网 时间:2024/06/05 06:08
由于在自己做的东西中用到了就总结一下,自己做了测试 在一个程序运行中如果按 返回键  分别执行了 : onpause()     onStop()   onDestory()方法    

 如果点击 home键 则执行了  onPause()   onStop()方法  ,呵呵这个方法的介绍可以在以后写程序中在不同的方法中执行不同的方法

 下边是实现两个按钮了 

1.实现home键    

  

[java] view plaincopy
  1. Intent intent = new Intent(Intent.ACTION_MAIN);  
  2.             intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 注意,这个地方最重要,关于解释,自己google吧  
  3.             intent.addCategory(Intent.CATEGORY_HOME);  
  4.             this.startActivity(intent);  



2.实现返回键

     1)监听返回键动作

[java] view plaincopy
  1. // 退出时提示  
  2. public boolean onKeyDown(int keyCode, KeyEvent event) {  
  3.     if (keyCode == KeyEvent.KEYCODE_BACK) {  
  4.         AlertDialog.Builder mDialog = new AlertDialog.Builder(  
  5.                 locResource.this);  
  6.         mDialog.setTitle("操作提示");  
  7.         mDialog.setMessage("确定退出吗?");  
  8.         mDialog.setPositiveButton("确定",  
  9.                 new DialogInterface.OnClickListener() {  
  10.                     public void onClick(DialogInterface dialog, int which) {  
  11.                         System.exit(0);  
  12.                     }  
  13.                 });  
  14.         mDialog.setNegativeButton("取消"null);  
  15.         mDialog.show();  
  16.     }  
  17.     return super.onKeyDown(keyCode, event);  
  18. }  
 2)自己写按钮实现方法

[java] view plaincopy
  1. AlertDialog.Builder mDialog = new AlertDialog.Builder(mainActivity.this);  
  2.     mDialog.setTitle("退出");  
  3.     mDialog.setMessage("确定要退出吗?");  
  4.     mDialog.setPositiveButton("确定",  
  5.             new DialogInterface.OnClickListener() {  
  6.                 public void onClick(DialogInterface dialog, int which) {  
  7.                     System.exit(0);  
  8.                 }  
  9.             });  
  10.     mDialog.setNegativeButton("取消"null);  
  11.     mDialog.show();