Android中在有TabHost情況下,OnKeyDown不能後退的解決辦法

來源:互聯網
上載者:User

最近在做一個項目,其中用到了TabActivity,想截取OnKeyDown事件來提示使用者退出程式在api lever 5以上有OnBackPressed重載函數,可以達到同樣的效果。

但是我一直沒有成功,偵錯工具發現,因為TabActivity壓根沒有擷取我按後退的事件,根本沒有捕獲OnKeyDown事件,弄了好久,我的退出提示代碼是這樣子寫的:

@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) {              new DialogUtil().Exitdialog(HomeActivity.this);            return true;          }          return false;  }

其中new DialogUtil().Exitdialog(HomeActivity.this);是彈出一個提示視窗!代碼如下:

public void Exitdialog(Context ctx) {          AlertDialog.Builder builder = new Builder(ctx);         View exitV=LayoutInflater.from(ctx).inflate(R.layout.exitdialog, null);        builder.setView(exitV);//設定對話方塊顯示的View對象                builder.setPositiveButton(R.string.app_exit_ok,          new android.content.DialogInterface.OnClickListener() {              @Override              public void onClick(DialogInterface dialog, int which) {                  dialog.dismiss();                  //AccoutList.this.finish();                   //System.exit(1);                   android.os.Process.killProcess(android.os.Process.myPid());              }          });          builder.setNegativeButton(R.string.app_exit_cancle,          new android.content.DialogInterface.OnClickListener() {              @Override              public void onClick(DialogInterface dialog, int which) {                  dialog.dismiss();              }          });          builder.create().show();      }

發現在自己的代碼也沒有寫錯,開是網上查了好久終於有了點頭緒了,解決了!原來是這樣子的,我的後退事件被我Tab頁的子Activity截取了

於是我在子activity中重載OnKeyDown函數,果然如我所料,成功了!

注本文部分內容轉載自http://www.eoeandroid.com/thread-83202-1-1.html

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.