Action Bar detect back button click in fragment

喜夏-厌秋 提交于 2019-12-02 00:25:16

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);
 }

I was facing the same problem, but then I put this code inside the activity and the back button worked from inside the fragment:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            Toast.makeText(getActivity(), "Back", Toast.LENGTH_LONG).show();
            break;
        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }
View cView = getLayoutInflater().inflate(R.layout.header, null);
cView.findViewById(R.id.btn_id).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
                     // Do stuff here.
    }
});
actionBar.setCustomView(cView);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!