【问题标题】:Buttons On Two Fragments Overlapping重叠的两个片段上的按钮
【发布时间】:2018-01-28 11:03:46
【问题描述】:

所以我有两个片段,比如 Fragment1 和 Fragment2 。两者都有自己的布局文件。在第一个片段 (Fragment1) 上有六个按钮。所以当我点击第一个按钮时,我希望它显示 Fragment2 但是当我点击第一个按钮时两者都是重叠的。

检查下面的屏幕截图

这是片段1

这是片段 2,它与片段 1 重叠

我使用了所有可能的解决方案,但没有一个有效。 我将背景设置为白色或黑色均匀图像。没有任何作用。

我在 mainActivity 上的代码

    public void button1click (View view) {
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.frag1,new Fragment2());
    fragmentTransaction.commit();
    fragmentTransaction.addToBackStack(null);
}

片段1

public class Fragment1 extends Fragment {
public class onClicks extends AppCompatActivity {
}
View myView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    myView = inflater.inflate(R.layout.fragment1_layout, container, false);
    return myView;
}}

片段2

public class Fragment2 extends Fragment {
public Fragment2 () {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment2_layout, container, false);
}}

fragment1_layout。 This is fragment1_layout

fragment2_layout。 THIS is the fragment2_layout

请检查有什么问题。

【问题讨论】:

  • 片段 1 是否也动态添加到视图中?还是在活动布局中是静态的。

标签: java android xml android-fragments overlapping


【解决方案1】:

文档建议您始终使用 FrameLayout 来替换片段。我在这一行的代码中看到了这个问题

 fragmentTransaction.replace(R.id.frag1,new Fragment2());

您似乎没有容器(FrameLayout)来替换其中的片段。要解决这个可能的设计问题,您应该为您的 Main Activity 创建一个 xml,例如添加一个带有 id "container" 的 FrameLayout。然后,以这种方式在代码中使用它

public void button1click (View view) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container,new Fragment2());
    fragmentTransaction.commit();
    fragmentTransaction.addToBackStack(null);
}

然后你应该在你的活动的 onCreate() 方法中将 fragment1 添加到你的容器中,这样你在打开应用程序时就不会出现黑屏

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多