Action Bar detect back button click in fragment

后端 未结 3 474
独厮守ぢ
独厮守ぢ 2021-01-21 06:30

I have a Fragment with action bar back button enabled in it.

Code :

@Override
    public void onAttach(Activity activity) {
        super.onAttach(activi         


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-21 07:09

    Better late than never, please try this>

     @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            mInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = mInflater.inflate(R.layout.fragment_layout, container, false);
            //set setHasOptionsMenu on true here on CreateView method
            setHasOptionsMenu(true);
            return view;
        }
    

    and implement

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
                if (item.getItemId() == android.R.id.home) {
                    if (getActivity() != null) {
                        getActivity().onBackPressed();
                    }
                    return true;
                };
                return super.onOptionsItemSelected(item);
     }
    

提交回复
热议问题