首页 > 解决方案 > 在片段中使用 NavController 控制子片段

问题描述

在我的应用程序中,我有 A 到 E 五个片段和 C1 C2 两个子片段。我尝试使用 NavController 来控制 C 中的 C1 和 C2,但我不知道如何在片段 C 中使用 NavController,它可以显示片段但不能将片段 C1 更改为 C2。当我点击按钮时,它会有动画,但没有改变片段

public class ChartFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_chart, container, false);

    BottomNavigationView navChartView = root.findViewById(R.id.nav_chart_view);
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_barchart, R.id.navigation_piechart)
            .build();
    NavController navController = NavHostFragment.findNavController(this);
    NavigationUI.setupWithNavController(navChartView, navController);
    return root;
}

}

这是我的fragmentC的xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".ui.ChartFragment">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/nav_view"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="0dp"
    android:layout_marginEnd="0dp"
    android:background="@color/halfWhite"
    app:layout_constraintTop_toTopOf="@id/nav_chart_fragment"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:menu="@menu/chart_nav_menu" />

<fragment
    android:id="@+id/nav_chart_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:defaultNavHost="true"
    app:layout_constraintBottom_toTopOf="@id/nav_view"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"
    app:navGraph="@navigation/chart_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>

标签: androidandroid-fragments

解决方案


推荐阅读