Activity中显示多个Fragment,如何实现
时间: 2024-01-29 18:01:58 浏览: 28
在Activity中显示多个Fragment,可以通过以下步骤实现:
1. 定义多个Fragment类,实现onCreateView方法,返回Fragment的布局。
```java
public class MyFragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my1, container, false);
return view;
}
}
public class MyFragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my2, container, false);
return view;
}
}
```
2. 在Activity的布局中添加多个Fragment的容器。
```xml
<LinearLayout
android:id="@+id/fragment_container1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"/>
<LinearLayout
android:id="@+id/fragment_container2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"/>
```
3. 在Activity中通过FragmentManager动态添加多个Fragment。
```java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取FragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();
// 开始Fragment事务1
FragmentTransaction transaction1 = fragmentManager.beginTransaction();
// 添加Fragment1到容器1中
MyFragment1 fragment1 = new MyFragment1();
transaction1.add(R.id.fragment_container1, fragment1);
// 提交事务1
transaction1.commit();
// 开始Fragment事务2
FragmentTransaction transaction2 = fragmentManager.beginTransaction();
// 添加Fragment2到容器2中
MyFragment2 fragment2 = new MyFragment2();
transaction2.add(R.id.fragment_container2, fragment2);
// 提交事务2
transaction2.commit();
}
}
```
通过以上代码,即可在Activity中动态显示多个Fragment的UI界面。需要注意的是,每个Fragment需要对应一个独立的容器,并且在添加Fragment时需要使用不同的事务。