gpt4 book ai didi

android - 在FrameLayout中动态添加多个 fragment

转载 作者:行者123 更新时间:2023-11-29 15:00:02 25 4
gpt4 key购买 nike

我正在尝试使用 FragmentTransaction 的 add() 方法将我正在创建的动态多个 fragment 添加到框架布局中。每次我尝试这样做时, fragment 只是一个一个地替换另一个。

这是我的代码:

public class FragmentMerchandSearch extends Fragment {


public FragmentMerchandSearch() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_merchand_search, container, false);
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
for(int i = 0; i < 10; i++){
Fragment newFragment = new FragmentMerchandPresentation();

ft.add(R.id.container_merchand_presentation_for_search, newFragment);

}
ft.commit();

return view;
}
}

这是FragmentMerchandPresentation的代码:

public class FragmentMerchandPresentation extends Fragment {

public FragmentMerchandPresentation(){

}

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


return view;
}
}

这是 fragment_merchand_search 的 XML:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/container_merchand_presentation_for_search">

</FrameLayout>

</LinearLayout>

</ScrollView>

和 fragment_presentation_merchand 的 XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hey !"/>
</LinearLayout>

最佳答案

您正在将 fragment 添加到 FrameLayout 中,这意味着一个在另一个之上。

要垂直添加它们,请使用 LinearLayout 作为容器。

只需将您的 fragment_merchand_search.xml 更改为:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
android:id="@+id/container_merchand_presentation_for_search"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

</ScrollView>

关于android - 在FrameLayout中动态添加多个 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48587720/

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