gpt4 book ai didi

android - 以编程方式替换 fragment

转载 作者:IT王子 更新时间:2023-10-28 23:29:33 27 4
gpt4 key购买 nike

我有三个 fragment ,如下图所示。我已经使用 .xml 文件在 LinearLayout 中添加了所有这三个 fragment ,当我的启动器 Activity 启动时,我使用 setContentView 加载该 .xml 布局。

我在 fragment 2 上有一些控件。点击任何一个加载fragment4 以编程方式使用 FragmentTransaction 和 commit 方法。此 fragment 已添加到屏幕,但问题是按语法添加的 fragment 4 占据了整个屏幕区域。可能是什么问题?

注意:在任何项目上单击 f2 我只想用新 fragment f4 替换 f2。请记住,我已通过 xml 布局文件添加了 f1、f2、f3,并以编程方式添加了新 fragment f4。

enter image description here

最佳答案

您应该始终以编程方式添加、删除和替换您的 fragment 。因此,我建议您将 F-1、F-2 和 F-3 fragment 替换为 FrameLayout 等容器。

基本上没有 <fragment/>作为 F-1 的元素,您将其设为 <FrameLayout/>元素。然后在 FragmentActivity 的 onCreate 中执行 fragment 事务:

Fragment1 f1 = new Fragment1();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.f1_container, f1); // f1_container is your FrameLayout container
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();

现在,假设您已为 F-1、F-2 和 F-3 执行此操作。然后,通过在 OnClickListener 中再次执行相同的操作,将 f2 替换为 f4。 :

public void onClick(View v) {
Fragment4 f4 = new Fragment4();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.f2_container, f4); // f2_container is your FrameLayout container
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}

关于android - 以编程方式替换 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10122570/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com