以编程方式返回到 backstack 中的上一个片段 [英] Programmatically go back to the previous fragment in the backstack

查看:16
本文介绍了以编程方式返回到 backstack 中的上一个片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

I found Trigger back-button functionality on button click in Android but 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):

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

调用 finish() 只会关闭我不感兴趣的活动.

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

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

Is there a better way to go about this?

推荐答案

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

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

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

这篇关于以编程方式返回到 backstack 中的上一个片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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