Add back button to action bar

后端 未结 11 1690
野趣味
野趣味 2020-12-07 16:23

I have been trying to add a back button to the action bar.

I want my view to look like this: \"enter

相关标签:
11条回答
  • 2020-12-07 17:07

    Use this to show back button and move to previous activity,

    final ActionBar actionBar = getSupportActionBar();
            assert actionBar != null;
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.back_dark);
    
    
    @Override
        public boolean onOptionsItemSelected(final MenuItem item) {
    
            switch (item.getItemId()) {
                case android.R.id.home:
                    onBackPressed();
                    return true;
                default:
                    return super.onOptionsItemSelected(item);
            }
        }
    
    0 讨论(0)
  • 2020-12-07 17:09

    Add

    actionBar.setHomeButtonEnabled(true);
    

    and then add the following

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

    As suggested by naXa I've added a check on the itemId, to have it work correctly in case there are multiple buttons on the action bar.

    0 讨论(0)
  • 2020-12-07 17:09

    You'll need to check menuItem.getItemId() against android.R.id.home in the onOptionsItemSelected method

    Duplicate of Android Sherlock ActionBar Up button

    0 讨论(0)
  • 2020-12-07 17:12

    Simpler and better: For API >= 16

    Simply add "parentActivityName" for each activity in Manifest. The back button will automatically take u to the parent activity.

    <activity
            android:name="com.example.myfirstapp.DisplayMessageActivity"
            android:label="@string/title_activity_display_message"
            android:parentActivityName="com.example.myfirstapp.MainActivity" >
    
    0 讨论(0)
  • 2020-12-07 17:13

    Firstly Use this:

    ActionBar bar = getSupportActionBar();
    bar.setDisplayHomeAsUpEnabled(true);
    

    Then set operation of button click in onOptionsItemSelected method

     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
             finish();
            return true;
         default:
            return super.onOptionsItemSelected(item);
      }
     }
    
    0 讨论(0)
提交回复
热议问题