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
Why it is not going back?
Add the following to your activity.You have to handle the click event of the back button.
Here is your code
You have to override onOptionsItemSelected and check the item's id, if it is equals with home button's id, just call onBackPressed method.
I would suggest not to handle "android.R.id.home" in onOptionsItemSelected as it is brittle. Rather you should override
onSupportNavigateUp
method.Note: If you are using
onOptionsItemSelected
, then you should return false as default otherwiseonSupportNavigateUp
method is not called.First of all, always see Android Guidelines http://developer.android.com/intl/pt-br/design/patterns/navigation.html to prevent Google blocks Android apps.
Try to add this code in your Activity
You have to define what should happen when you click on that button, this can be done in your second activity's onOptionsItemSelected method. Notice the
android.R.id.home
constant which refers to the activity's back button that you want to use.