用Fragmentcontainerview添加多个Fragment的完整例子
时间: 2024-02-01 09:16:39 浏览: 157
一个Activity中多个Fragment实现沉浸式状态栏的解决方法
这是一个使用FragmentContainerView添加多个Fragment的完整例子:
1. 在布局文件中添加一个FragmentContainerView:
```xml
<androidx.fragment.app.FragmentContainerView
android:id="@+id/container"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
```
2. 创建一个Navigation Graph(例如`nav_graph.xml`)来定义Fragment之间的导航:
```xml
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_graph"
app:startDestination="@id/fragment1">
<fragment
android:id="@+id/fragment1"
android:name="com.example.Fragment1"
android:label="Fragment 1"
tools:layout="@layout/fragment1" />
<fragment
android:id="@+id/fragment2"
android:name="com.example.Fragment2"
android:label="Fragment 2"
tools:layout="@layout/fragment2" />
</navigation>
```
3. 在Activity中获取FragmentContainerView并设置NavController:
```java
public class MainActivity extends AppCompatActivity {
private NavController navController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentContainerView container = findViewById(R.id.container);
navController = Navigation.findNavController(this, R.id.container);
}
@Override
public boolean onSupportNavigateUp() {
return navController.navigateUp() || super.onSupportNavigateUp();
}
}
```
4. 在Fragment中使用NavController导航到另一个Fragment:
```java
public class Fragment1 extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1, container, false);
Button button = view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NavDirections action = Fragment1Directions.actionFragment1ToFragment2();
Navigation.findNavController(v).navigate(action);
}
});
return view;
}
}
```
这样就可以使用FragmentContainerView添加多个Fragment并在它们之间进行导航了。
阅读全文