【问题标题】:Switch BottomNavigationDrawer fragments on button click在按钮单击时切换底部导航抽屉片段
【发布时间】:2021-11-07 13:17:15
【问题描述】:

我创建了一个 Android 应用,并为 MainActivity 选择了 BottomNavigationDrawer 模板。 Android Studio 为我生成了所有代码,这很好,但我在其中一个fragments 中放置了一个按钮,当用户单击该button 时,我想导航到另一个fragment。我在点击按钮时做了这样的事情:

FragmentTransaction ft = getActivity.getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.container, new HomeFragment(), fragment.toString());
        ft.addToBackStack(null);
        ft.commit();

这是我的activity_main.xml,由 Android Studio 生成:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 

    xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/container"
        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="?android:attr/windowBackground"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:menu="@menu/bottom_nav_menu" />
    
        <fragment
            android:id="@+id/nav_host_fragment_activity_main"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toTopOf="@id/nav_view"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:navGraph="@navigation/mobile_navigation" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>

我所有的其他片段都在res 文件夹内的navigation 文件夹中,这也是默认情况下由Android Studio 完成的。我在上面的replace 中传递的id 是罪魁祸首,我不知道我应该在这里传递哪个id

【问题讨论】:

    标签: java android xml android-studio


    【解决方案1】:

    请提供更多细节以获得更好的帮助。但是,请将这个 setReorderingAllowed 放在 commit Home 片段之前。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      • 2013-10-26
      • 1970-01-01
      • 2020-03-09
      相关资源
      最近更新 更多