Android 以编程方式返回到 backstack 中的上一个片段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10863572/
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 05:16:27  来源:igfitidea点击:

Programmatically go back to the previous fragment in the backstack

androidandroid-fragmentsback-stack

提问by Aske B.

Say I have an activity that has fragments added programmatically:

假设我有一个以编程方式添加片段的活动:

private void animateToFragment(Fragment newFragment, String tag) {
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_container, newFragment, tag);
    ft.addToBackStack(null);
    ft.commit();
}

What is the best way to return to the previous fragment that was visible?

返回到上一个可见片段的最佳方法是什么?

I found Trigger back-button functionality on button click in Androidbut I'm thinking simulating a back key event isn't the right way to go about it (and I can't get it to work either):

我发现在 Android 中单击按钮时触发后退按钮功能,但我认为模拟后退键事件不是正确的方法(而且我也无法让它工作):

dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));

Calling finish()just closes the activity which I'm not interested in.

打电话finish()只会关闭我不感兴趣的活动。

Is there a better way to go about this?

有没有更好的方法来解决这个问题?

回答by stuckless

Look at the getFragmentManager().popBackStack()methods (there are several to choose from)

getFragmentManager().popBackStack()方法(有几种可以选择)

http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack()

http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack()

回答by Kyle Falconer

To elaborate on the other answers provided, this is my solution (placed in an Activity):

为了详细说明提供的其他答案,这是我的解决方案(放置在活动中):

@Override
public void onBackPressed(){
    FragmentManager fm = getFragmentManager();
    if (fm.getBackStackEntryCount() > 0) {
        Log.i("MainActivity", "popping backstack");
        fm.popBackStack();
    } else {
        Log.i("MainActivity", "nothing on backstack, calling super");
        super.onBackPressed();  
    }
}

回答by Jabeer

When we are updating/add the fragments,

当我们更新/添加片段时,

Should Include the .addToBackStack().

应包括.addToBackStack().

getSupportFragmentManager().beginTransaction()
    .add(detailFragment, "detail") // Add this transaction to the back stack (name is an optional name for this back stack state, or null).
    .addToBackStack(null)
    .commit();

After that if we give the getFragments.popBackStackImmediate()will return true if we add/update the fragments, and move back to the current screen.

之后,如果我们getFragments.popBackStackImmediate()添加/更新片段,将返回 true,并返回当前屏幕。

回答by Avijit Biswas

Add those line to your onBackPressed() Method. popBackStackImmediate() method will get you back to the previous fragment if you have any fragment on back stack `

将这些行添加到您的 onBackPressed() 方法中。如果返回堆栈上有任何片段,popBackStackImmediate() 方法将使您返回到前一个片段`

if(getFragmentManager().getBackStackEntryCount() > 0){
     getFragmentManager().popBackStackImmediate();
}
else{
    super.onBackPressed();
}

`

`

回答by Giedrius ?likas

This solution works perfectly for bottom bar based fragment navigation when you want to close the app when back pressed in primary fragment.

当您想在主片段中回按时关闭应用程序时,此解决方案非常适合基于底部栏的片段导航。

On the other hand when you are opening the secondary fragment (fragment in fragment) which is defined as "DetailedPizza" in my code it will return the previous state of primary fragment. Cheers !

另一方面,当您打开在我的代码中定义为“DetailedPizza”的次要片段(片段中的片段)时,它将返回主要片段的先前状态。干杯!

Inside activities on back pressed put this:

背面的内部活动按下了这个:

Fragment home = getSupportFragmentManager().findFragmentByTag("DetailedPizza");

if (home instanceof FragmentDetailedPizza && home.isVisible()) {
    if (getFragmentManager().getBackStackEntryCount() != 0) {
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }
} else {
    //Primary fragment
    moveTaskToBack(true);
}

And launch the other fragment like this:

并像这样启动另一个片段:

Fragment someFragment = new FragmentDetailedPizza();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container_body, someFragment, "DetailedPizza");
transaction.addToBackStack("DetailedPizza");
transaction.commit();

回答by Biplob Das

These answers does not work if i don't have addToBackStack() added to my fragment transaction but, you can use:

如果我没有将 addToBackStack() 添加到我的片段事务中,这些答案不起作用,但是,您可以使用:

getActivity().onBackPressed();

from your any fragment to go back one step;

从你的任何片段往回走一步;

回答by Grzesiek Eman

I came here looking or the same idea, and in the meantime i came up with own, which I believe is not that bad and works if with ViewPager.

我来到这里寻找或相同的想法,同时我想出了自己的想法,我相信这不是那么糟糕,如果与 ViewPager 一起工作。

So what I did, is to override the onBackPressed method in the parent activity that holds the viewPager, and set it to always go back minus 1 position until it reaches the first fragment, then closes the activity.

所以我所做的是覆盖保存 viewPager 的父活动中的 onBackPressed 方法,并将其设置为始终返回负 1 位置,直到到达第一个片段,然后关闭该活动。

@Override
public void onBackPressed() {
    if(viewPager.getCurrentItem()>0){
        viewPager.setCurrentItem(viewPager.getCurrentItem()-1);
    } else {
        super.onBackPressed();
        this.close();
    }
}

private void close(){
    this.finish();
}

This might have a downfalls, like it only goes back one way left each time, so it might not work great if there are tabs and you switch positions with fragments skipped, ( going from 0 to 2, and then pressing back would put you on 1, instead of 0)

这可能有一个缺点,就像它每次只向左返回一个方向,所以如果有选项卡并且你在跳过片段的情况下切换位置,它可能不会很好用,(从 0 到 2,然后按回会让你1, 而不是 0)

For my case tho, with 2 fragments in viewPager without tabs, it does the job nicely.

对于我的情况,在没有选项卡的 viewPager 中有 2 个片段,它可以很好地完成工作。

回答by Saurabh Singh

To make that fragment come again, just add that fragment to backstack which you want to come on back pressed, Eg:

要使该片段再次出现,只需将该片段添加到您想要返回的 backstack,例如:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Fragment fragment = new LoginFragment();
        //replacing the fragment
        if (fragment != null) {
            FragmentTransaction ft = ((FragmentActivity)getContext()).getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.content_frame, fragment);
            ft.addToBackStack("SignupFragment");
            ft.commit();
        }
    }
});

In the above case, I am opening LoginFragmentwhen Button buttonis pressed, right now the user is in SignupFragment. So if addToBackStack(TAG)is called, where TAG = "SignupFragment", then when back button is pressed in LoginFragment, we come back to SignUpFragment.

在上述情况下,我打开LoginFragment的时候Button button按下,现在用户在SignupFragment。所以如果addToBackStack(TAG)被调用, where TAG = "SignupFragment",然后当返回按钮被按下时LoginFragment,我们回到SignUpFragment

Happy Coding!

快乐编码!

回答by Baljinder Maan

By adding fragment_tran.addToBackStack(null)on last fragment, I am able to do come back on last fragment.

通过添加fragment_tran.addToBackStack(null)最后一个片段,我可以回到最后一个片段。

adding new fragment:

添加新片段

view.findViewById(R.id.changepass).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.container, new ChangePassword());
            transaction.addToBackStack(null);
            transaction.commit();
        }
    });

回答by Piyush MandaliYa

Programmatically go back to the previous fragment using following code.

使用以下代码以编程方式返回上一个片段。

if ( getFragmentManager().getBackStackEntryCount() > 0) 
{
          getFragmentManager().popBackStack();
          return;
}
super.onBackPressed();