I have created an app and wanted a back button on my action bar to navigate back to the previous page using Android Studio. I have looked at a number of examples but keep getting errors under setDisplayHomeAsUpEnabled
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
public boolean onOptionsItemSelected(MenuItem item) {
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
Assuming that you have a DetailActivity and you need back button to MainActivity. First change your manifest to for DetailActivity
<activity
android:name=".DetailActivity"
android:label="@string/title_activity_detail"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.MainActivity"/>
</activity>
and in onCreate
of DetailActivity
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
will fix things. This is the simplest implementation.
Use this in onCreate()
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
Than add this listener in your MainActivity.java
class
protected OnBackPressedListener onBackPressedListener;
public interface OnBackPressedListener {
void doBack();
}
public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) {
this.onBackPressedListener = onBackPressedListener;
}
@Override
public void onBackPressed() {
if (onBackPressedListener != null)
onBackPressedListener.doBack();
else
super.onBackPressed();
}
So now in your Fragment class you can implements MainActivity.OnBackPressedListener
and than:
@Override
public void doBack() {
//Do on back pressed operation
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With