Android 添加没有事务的片段
我试图在我的活动中动态地将一个片段替换为另一个片段。
看起来您无法用动态创建的片段替换布局文件中静态定义的片段: Android:无法用另一个片段替换一个片段
建议的解决方案是在onCreate方法中动态添加原始Fragment:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ShelfFragment shelves = new ShelfFragment();
ft.add(R.id.left_fragment, shelves);
ft.addToBackStack(null);
ft.commit();
}
这可行,但是当用户按下后退按钮时,原始Fragment被删除而不是关闭Activity,因为FragmentTransaction将其添加到FragmentManager堆栈中。
有没有办法在没有事务/堆栈条目的情况下将初始片段添加到我的活动中?
I'm trying to replace a Fragment with another Fragment dynamically in my activity.
It looks like you can't replace a fragment statically defined in a layout file, with a dynamically created fragment:
Android: can't replace one fragment with another
The suggested solution was to add the original Fragment dynamically in the onCreate method:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ShelfFragment shelves = new ShelfFragment();
ft.add(R.id.left_fragment, shelves);
ft.addToBackStack(null);
ft.commit();
}
This works, but when the user presses the back button, the original Fragment is removed instead of closing the Activity because the FragmentTransaction added it to the FragmentManager stack.
Is there a way to add the initial Fragment to my activity without a Transaction/Stack entry?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要将其添加到后台堆栈。删除
ft.addToBackStack(null);
行,仅当您希望能够使用后退按钮返回到先前状态时才需要此行。Don't add it the backstack. Delete the
ft.addToBackStack(null);
line, you only need this if you want to be able to go back to the previous state with the back button.