In many apps (Calendar, Drive, Play Store) when you tap a button and enter a new activity, the icon in the title bar turns into a back button, but for the app I am making, i
For kotlin :
override fun onOptionsItemSelected(item: MenuItem): Boolean {
onBackPressed();
return true;
}
I needed to mix some answers to get the right answer for me because my app has 3 activities that can go and back at any time. Activity1 > Activity2 > Activity3. When I was doing something on my activity3, the back button was backing correctly to Activity2. However, from the Activity2, using finish()
, it was backing to Activity3 and not Activity1. And I'm extending AppCompatActivity. So, my solution was:
public class Activity2 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
...
getSupportActionBar().setHomeButtonEnabled(true);
}
}
on AndroidManifest.xml:
<activity android:name=".activities.Activity2"
android:parentActivityName="com.example.appname.activities.Activity1">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.appname.activities.Activity1" />
</activity>
and finally, the action button on my menu (actionbar):
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
...
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
Using NavUtils.navigateUpFromSameTask(this);
worked for me, instead of finish()
.
use this code
@Override
public void onCreate(Bundle savedInstanceState) {
...
getActionBar().setDisplayHomeAsUpEnabled(true);
}
after that write this code in onOptionsItemSelected
method
int id = item.getItemId();
if (id==android.R.id.home) {
finish();
}
first of all in onCreate Function add the following line
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
and then add the following function in the code:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
If you are using an ActionBar you're going to want to read up on this documentation http://developer.android.com/reference/android/app/ActionBar.html#setDisplayHomeAsUpEnabled(boolean)
Then you have to overwrite the method onOptionsItemSelected(MenuItem) and look for the android.R.id.home event to come in. Then you know the user has clicked on that back button on the actionbar
I have finally managed to properly add back button to actionbar/toolbar
@Override
public void onCreate(Bundle savedInstanceState) {
...
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}