Search code examples
androidandroid-actionbar

How to display back button on action bar in android another activity


I want to need back button on action bar when I move another activity from main activity. Please help me how can I do now.

I am new in android development, please explain something details.

Thank you.


Solution

  • Just add code this in the onCreate method of your [CurrentActivity].java file.

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    

    And this line of code will just add a back button in your Action Bar, but nothing would happen after tapping that right now.

    And add this in your [CurrentActivity].java, this will add the working of that button:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
    
                Intent intent = new Intent(CurrentActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
                return true;
    
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    

    And replace CurrentActivity to your activity name and replace MainActivity to the activity you want to send user after pressing back button