redblood
redblood

Reputation: 542

Back button is Not working in actionBar

By pressing actionBar icon I should go to previous Fragment but it is not going. I mean nothing happen when I press actionbar icon.

public class SecFrag extends Fragment {

// constructor and onCreateView goes here

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Toolbar toolbar = (Toolbar)getActivity().findViewById(R.id.toolbar);
        ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
        ActionBar actionBar=((AppCompatActivity)     getActivity()).getSupportActionBar();
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);


        recyclerView= (RecyclerView) getActivity().findViewById(R.id.recyclerViewInSecFragment);
        RecyclerAdapter adapter=new RecyclerAdapter(MainActivity.musicList,null,null);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Log.e("SEC",item.getItemId()+"");
        switch (item.getItemId())
        {
            case android.R.id.home:
            {
                Log.e("SECFRAG","CLICKED");
                break;
            }
           default:break;
        }
        return super.onOptionsItemSelected(item);
    }
}

So it's not going to trigger android.R.id.home in the switch statement. So please suggest why this is not working.

Upvotes: 3

Views: 1032

Answers (1)

Ahmed Hegazy
Ahmed Hegazy

Reputation: 12615

You need to instruct the android stack that your fragment will handle the options menu instead of the holder activity by calling setHasOptionsMenu(true) and it's recommended by the docs to put it in your fragment's onCreate() callback. This will make your log message to be called appropriately.

Upvotes: 2

Related Questions