androidandroid-fragmentsandroid-actionbarandroid-navigationup-button

How to hide the "Up button" in the top Fragment and show it in other Fragments?


In a Bluetooth-related app (with minSdkVersion="18") I have a single MainActivity.java, displaying one of the following 3 UI Fragments:

screenshot

To display an "Up button" and handle the "Back button" I have the following code in place:

public class MainActivity extends Activity 
                          implements BleWrapperUiCallbacks {

    // set in onResume() of each fragment
    private Fragment mActiveFragment = null;

´   @Override
    public void onBackPressed() {
        if (!getFragmentManager().popBackStackImmediate())
            super.onBackPressed();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        setContentView(R.layout.activity_root);
        getActionBar().setDisplayHomeAsUpEnabled(true);

        if (savedInstanceState == null) {
            Fragment fragment = new MainFragment();
            getFragmentManager().beginTransaction()
                .replace(R.id.root, fragment, "main")
                .commit();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                getFragmentManager().popBackStackImmediate();
                break;

            case R.id.action_settings:
                Fragment fragment = new SettingsFragment();
                getFragmentManager().beginTransaction()
                    .addToBackStack(null)
                    .replace(R.id.root, fragment, "settings")
                    .commit();
                break;
        }

        return super.onOptionsItemSelected(item);
    }

This works well, but has a cosmetic problem, that the "Up button" is still displayed when the MainFragment.java is being displayed - as you can see on the left side of the above screenshot.

I have tried calling

getActionBar().setHomeButtonEnabled(false);

when that fragment is being active, but that only disables the "Up button" - without really hiding it.


Solution

  • You are in luck because in API level 18 there is this:

    getActionBar().setHomeAsUpIndicator(R.drawable.ic_yourindicator);  
    

    for support library, it is:

    getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_yourindicator);  
    

    So now depending upon what fragment you are in, you can change the icon of "up" button.

    Also, try this:

    getActionBar().setDisplayHomeAsUpEnabled(false);
    

    Set whether home should be displayed as an "up" affordance.