Check if back key was pressed in android?

前端 未结 5 1514
孤街浪徒
孤街浪徒 2020-12-15 05:38

Say I\'m on my main activity and I start a new activity

MainActivity > NewActivity

And from NewActivity I press the back ke

5条回答
  •  轮回少年
    2020-12-15 06:20

    I try the below method to detect the back button pressed on the action bar in activity by the first method and the second one is used to detecting the mobile hardware button back or kill activity button.

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public void onBackPressed() {
        setResult(RESULT_CANCELED);
        super.onBackPressed();
    }
    

提交回复
热议问题