Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add back button on ActionBar in Android Studio?

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);

}
like image 796
Craig Gallagher Avatar asked Dec 05 '15 20:12

Craig Gallagher


2 Answers

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.

like image 119
adnbsr Avatar answered Nov 05 '22 17:11

adnbsr


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
}
like image 1
Michele Lacorte Avatar answered Nov 05 '22 19:11

Michele Lacorte