How to close the current fragment by using Button

2019-01-21 04:51发布

I have try to close the current fragment by using Imagebutton.

I am in Fragment-A and it will turn to the Fragment-B when I click the button.

And when I click the button at Fragment-B , it will turn to the Fragment-C and close the Fragment-B.

If I click the back button at Fragment-C , it will back to the Fragment-A.

The code I have try is like the following

camera_album = (ImageButton) view.findViewById(R.id.camera_album);

        camera_album.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {

                            closefragment();
                Fragment fragment = FileBrowserFragment.newInstance(null, null, null) ;
                MainActivity.addFragment(LocalFileBrowserFragment.this, fragment) ;


            }
        });

    private void closefragment() {
        getActivity().getFragmentManager().beginTransaction().remove(this).commit();
    }

When I click the back button at fragment-B , it turn to the Fragment-C.

But when I click the back button on Fragment-C , it doesn't back to the Fragment-A. It back to the empty background. If I want to back to Fragment-A , I have to click the back button once again.

SO , it seem doesn't close the current fragment complete.

How to finish the current fragment like the back button of Android ?

11条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-21 05:01

Try this:

ft.addToBackStack(null);   // ft is FragmentTransaction

So, when you press back-key, the current activity (which holds multiple fragments) will load previous fragment rather than finishing itself.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-21 05:02

If you need to handle the action more specifically with the back button you can use the following method:

    view.setFocusableInTouchMode(true);
    view.requestFocus();
    view.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if( keyCode == KeyEvent.KEYCODE_BACK )
            {
                onCloseFragment();
                return true;
            } else {
                return false;
            }
        }
    });
查看更多
贪生不怕死
4楼-- · 2019-01-21 05:03

This is a Kotlin way of doing this, I have created button in fragment layout and then set onClickListner in onViewCreated.

according to @Viswanath-Lekshmanan comment

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) 
{
     super.onViewCreated(view, savedInstanceState)

     btn_FragSP_back.setOnClickListener {
        activity.onBackPressed()
    }
}
查看更多
太酷不给撩
5楼-- · 2019-01-21 05:04

getActivity().onBackPressed does the all you need. It automatically calls the onBackPressed method in parent activity.

查看更多
淡お忘
6楼-- · 2019-01-21 05:05

For those who need to figure out simple way

Try getActivity().onBackPressed();

查看更多
你好瞎i
7楼-- · 2019-01-21 05:05

Try this one

getActivity().finish();
查看更多
登录 后发表回答