OnOptionsItemSelected not called when button is clicked in action bar - Android

When I click the back button of my action bar, the onOptionsItemSelected method of my fragment has never been called. I want to go to the previous snippet when I clicked the button, but it never calls this method. This is the code for the snippet, what could this be the problem?

public class MyFragment extends Fragment {


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ((ActionBarActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    ((ActionBarActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);

    setHasOptionsMenu(true);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    // Get item selected and deal with it
    switch (item.getItemId()) {
        case android.R.id.home:
            //called when the up affordance/carat in actionbar is pressed
            getActivity().onBackPressed();
            return true;
    }
    return false;
}

      

Thanks in advance.

+3


source to share


1 answer


First of all, this will be obtained in the base activity, not in the fragment.
Add your previous fragment to the back stack.
And from this snippet popup

if (ID == android.R.id.home) {getSupportFragmentManager () popBackStack (). }



And to check which fragment it was called from, use:
if (fragment instanceof MyFragment)
You're done !!

-1


source







All Articles