Android architecture component navigation: toolbar back button missing, back not working

前端 未结 1 1909
清歌不尽
清歌不尽 2021-01-24 07:36

I\'m trying the jetpack navigation and can\'t show the navigation back button when I move to a new fragment.

NavigationActivity.kt

class NavActivity : Ap         


        
相关标签:
1条回答
  • 2021-01-24 08:05

    Edit: Your DetailFragment contains the line

    DataBindingUtil.setContentView<FragmentDetailBinding>(requireActivity(),
        R.layout.fragment_detail)
    

    which is resetting the content of your Activity to only be your fragment_detail layout, wiping out the NavHostFragment and everything else.

    You should be using DataBindingUtil.bind<FragmentDetailBinding>(view)!! instead.

    Original answer (you should still do this, but the above answer is actually what solves the problem)

    Your ConstraintLayout is missing quite a few constraints (your views should be a vertical chain, where every app:layout_constraintTop_toBottomOf has an alternative app:layout_constraintBottom_toTopOf on the other element, etc.).

    Since you have a single set of three vertically aligned items, you don't need a ConstraintLayout - just a LinearLayout is enough:

    <?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout
        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:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".views.NavActivity">
    
        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_height="?attr/actionBarSize"
            android:elevation="4dp"
            android:background="?attr/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            android:layout_width="match_parent"/>
    
        <fragment
            android:id="@+id/navigation_graph"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:defaultNavHost="true"
            app:navGraph="@navigation/navigation_graph"/>
    
        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bottom_nav_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:menu="@menu/menu_bottom_nav" />
    </LinearLayout>
    
    0 讨论(0)
提交回复
热议问题