Android 如何像后退按钮一样使用 Button 关闭当前片段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20812922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:30:46  来源:igfitidea点击:

How to close the current fragment by using Button like the back button?

androidandroid-fragmentsactivity-finish

提问by Wun

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

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

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

我在 Fragment-A 中,当我单击按钮时它会变成 Fragment-B。

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

当我单击 Fragment-B 上的按钮时,它将转向 Fragment-C 并关闭 Fragment-B。

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

如果我单击 Fragment-C 处的后退按钮,它将返回到 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.

当我单击 fragment-B 处的后退按钮时,它会转到 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.

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

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

所以,似乎没有完成当前片段的关闭。

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

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

采纳答案by S.D.

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

从 Fragment A 到 B,用 B 替换 A 并使用addToBackstack()before commit()

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.

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

回答by Wun

I change the code from getActivity().getFragmentManager().beginTransaction().remove(this).commit();

我将代码从 getActivity().getFragmentManager().beginTransaction().remove(this).commit();

to

getActivity().getFragmentManager().popBackStack();

And it can close the fragment.

它可以关闭片段。

回答by Viswanath Lekshmanan

For those who need to figure out simple way

对于那些需要找出简单方法的人

Try getActivity().onBackPressed();

尝试 getActivity().onBackPressed();

回答by Shylendra Madda

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.

因此,当您按下back-key 时,当前活动(包含多个片段)将加载前一个片段而不是自行完成。

回答by Farruh Habibullaev

getActivity().onBackPresseddoes the all you need. It automatically calls the onBackPressedmethod in parent activity.

getActivity().onBackPressed做你需要的一切。它会自动调用父活动中的onBackPressed方法。

回答by Abdul Rehman

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

这是执行此操作的 Kotlin 方式,我在片段布局中创建了按钮,然后在 onViewCreated 中设置了 onClickListner。

according to @Viswanath-Lekshmanan comment

根据@Viswanath-Lekshmanan 的评论

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

     btn_FragSP_back.setOnClickListener {
        activity?.onBackPressed()
    }
}

回答by Bruno L.

Button ok= view.findViewById(R.id.btSettingOK);
Fragment me=this;
ok.setOnClickListener( new View.OnClickListener(){
    public void onClick(View v){
     getActivity().getFragmentManager().beginTransaction().remove(me).commit();
    }
});

回答by None

Try this:

尝试这个:

public void removeFragment(Fragment fragment){
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    fragmentTransaction.remove(fragment);
    fragmentTransaction.commit();
}

回答by user8595527

You can try this logic because it is worked for me.

你可以试试这个逻辑,因为它对我有用。

frag_profile profile_fragment = new frag_profile();

boolean flag = false;
@SuppressLint("ResourceType")
public void profile_Frag(){
    if (flag == false) {
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        manager.getBackStackEntryCount();
        transaction.setCustomAnimations(R.anim.transition_anim0, R.anim.transition_anim1);
        transaction.replace(R.id.parentPanel, profile_fragment, "FirstFragment");
        transaction.commit();
        flag = true;
    }

}

@Override
public void onBackPressed() {
    if (flag == true) {
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        manager.getBackStackEntryCount();
        transaction.remove(profile_fragment);
        transaction.commit();
        flag = false;
    }
    else super.onBackPressed();
}

回答by user8595527

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