Search code examples
javaandroidandroid-fragmentsandroid-actionbar

Android Studio: How to implement backbutton in ActionBar from Fragments


I'm having trouble implementing a backbutton in the ActionBar in a Fragment. Since this is a Fragment I don't have access to getSupportActionBar(); and each time I use this, or similar code:

ActionBar actionBar = getActivity().getActionBar();
          actionBar.setDisplayHomeAsUpEnabled(true); 

only results in NullPointerExceptions.

I've looked at numerous similar questions on StackOverflow but most of them are specified to Activities or AppCompatActivities, which do not work in Fragments. Using

getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);

only results in NullPointerExceptions. The other similar questions and answers have not helped me with this problem so I had to create a new topic.

This is where I get the error:

public class ExampleFragment extends Fragment{
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();

        ActionBar actionBar = getActivity().getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true); //This results in NullPointerException

        inflater.inflate(R.menu.example_menu, menu);

        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                getActivity().getSupportFragmentManager().popBackStack();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Solution

  • I did not get this to work so I changed the structure of the View and made it to an Activity which has more support in dealing with this issue.

    @Override
        protected void onCreate(@Nullable Bundle savedInstance){
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    
    @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
    
            if (id == android.R.id.home) {
                finish();
            }
    
            return super.onOptionsItemSelected(item);
        }