如何像后退按钮一样使用 Button 关闭当前片段? [英] How to close the current fragment by using Button like the back button?

查看:29
本文介绍了如何像后退按钮一样使用 Button 关闭当前片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 Imagebutton 关闭当前片段.

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

我在 Fragment-A 中,当我单击按钮时它会转到 Fragment-B.

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

当我点击 Fragment-B 的按钮时,它会转向 Fragment-C 并关闭 Fragment-B.

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

如果我点击 Fragment-C 处的后退按钮,它将返回到 Fragment-A.

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

我尝试的代码如下

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

当我单击 fragment-B 处的后退按钮时,它会转到 Fragment-C.

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

但是当我单击 Fragment-C 上的后退按钮时,它不会返回到 Fragment-A.它回到了空旷的背景.如果我想回到 Fragment-A ,我必须再次点击返回按钮.

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 ,它似乎没有关闭当前片段完成.

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

如何像Android的后退按钮一样完成当前片段?

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

推荐答案

从 Fragment A,转到 B,用 B 替换 A 并在 commit()<之前使用 addToBackstack()/代码>.

From Fragment A, to go to B, replace A with B and use addToBackstack() before commit().

现在从Fragment B,到C,首先使用popBackStackImmediate(),这将带回A.现在用C替换A,就像第一次交易一样.

Now From Fragment B, to go to C, first use popBackStackImmediate(), this will bring back A. Now replace A with C, just like the first transaction.

这篇关于如何像后退按钮一样使用 Button 关闭当前片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆