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

来源:互联网 发布:jquery.eraser.js 编辑:程序博客网 时间:2024/06/05 00:17

转自:点击打开链接

由于在自己做的东西中用到了就总结一下,自己做了测试 在一个程序运行中如果按 返回键  分别执行了 : onpause()     onStop()   onDestory()方法    

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

 下边是实现两个按钮了


1.实现home键   

    Intent intent = new Intent(Intent.ACTION_MAIN);                  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 注意,这个地方最重要,关于解释,自己google吧                  intent.addCategory(Intent.CATEGORY_HOME);                  this.startActivity(intent);  

2.实现返回键

     1)监听返回键动作

// 退出时提示  public boolean onKeyDown(int keyCode, KeyEvent event) {      if (keyCode == KeyEvent.KEYCODE_BACK) {          AlertDialog.Builder mDialog = new AlertDialog.Builder(                  locResource.this);          mDialog.setTitle("操作提示");          mDialog.setMessage("确定退出吗?");          mDialog.setPositiveButton("确定",                  new DialogInterface.OnClickListener() {                      public void onClick(DialogInterface dialog, int which) {                          System.exit(0);                      }                  });          mDialog.setNegativeButton("取消", null);          mDialog.show();      }      return super.onKeyDown(keyCode, event);  
 2)自己写按钮实现方法
    AlertDialog.Builder mDialog = new AlertDialog.Builder(mainActivity.this);          mDialog.setTitle("退出");          mDialog.setMessage("确定要退出吗?");          mDialog.setPositiveButton("确定",                  new DialogInterface.OnClickListener() {                      public void onClick(DialogInterface dialog, int which) {                          System.exit(0);                      }                  });          mDialog.setNegativeButton("取消", null);          mDialog.show();