Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display back button of action bar is not going back in Android

I am developing an Android app. I am using ActionBar with AppCompactActivity. In my app, I add back button to action bar. But when I click on it, it is not going back to the previous activity. For example, I start activity 2 from activity 1. Activity 2 contains action bar with back button. But when I click on action bar back button of activity 2, it is not going back to activity 1.

This is how I set action bar for activity 2:

public class EditProfileActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_profile);
        Toolbar toolbar = (Toolbar)findViewById(R.id.profile_action_toolbar);
        setSupportActionBar(toolbar);
        setTitle("Edit Profile");
        ActionBar actionBar= getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}

This is how I started activity 2 from activity 1:

Intent i = new Intent(MainActivity.this,SecondActivity.class);
                    startActivity(i);

It is not going back when I click this button

enter image description here

Why it is not going back?

like image 352
Wai Yan Hein Avatar asked Apr 06 '16 16:04

Wai Yan Hein


People also ask

Where is my back button?

1) Tap the Settings icon on your phone. It can be found in your app list. 3) Find any mention of Gesture Control or Navigation Control. 4) Change from Gesture navigation to 3-button navigation, and you're done!

How do I get rid of the back arrow on my android toolbar?

setDisplayShowHomeEnabled(false); //disable back button getActionBar(). setHomeButtonEnabled(false); In a older android phone, the back button is removed with these two code lines.


1 Answers

Add the following to your activity.You have to handle the click event of the back button.

@Override
 public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()){
         case android.R.id.home:
              onBackPressed();
              return true;
       }
   return super.onOptionsItemSelected(item);
 }
like image 51
Ravi Theja Avatar answered Oct 20 '22 16:10

Ravi Theja