how to override action bar back button in android?

前端 未结 10 702
孤街浪徒
孤街浪徒 2020-11-30 03:40

I want to customize the activity back button in action bar, not in hard key back button. I have overriden the onBackPressed() method. It works with my emulator

10条回答
  •  醉梦人生
    2020-11-30 03:56

    Sorry mine is a late answer, but for anyone else arriving at this page with the same question, I had tried the above:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      ...
      if (item.getItemId() == android.R.id.home) {
        ....
      }
      ....
    }
    

    but this failed to catch the "Back" button press.

    Eventually I found a method that worked for me on https://stackoverflow.com/a/37185334/3697478 which is to override the "onSupportNavigateUp()" as I am using the actionbar from the "AppCompatActivity" support library. (There is an equivalent "onNavigateUp()" for the newer actionbar/toolbar library.)

    @Override
    public boolean onSupportNavigateUp(){  
      finish();  
      return true;  
    }
    

    and I removed the "android:parentActivityName=".MainActivity" section from the manifest file.

提交回复
热议问题