Привязка представления Android: при доступе к NavHostFragment из включенного XML-макета

#android #layout #navigation #include #fragment

#Android #макет #навигация #включить #фрагмент

Вопрос:

У меня есть activity_main.xml , с ViewBinding включенным генерирует ActivityMainBinding класс отлично. У меня есть другой content_main.xml макет, который включен в этот макет, как показано ниже:

activity_main.xml

  <androidx.coordinatorlayout.widget.CoordinatorLayout
        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"
        tools:context=".MainActivity">

        <com.google.android.material.appbar.AppBarLayout
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:theme="@style/AppTheme.AppBarOverlay">

            <androidx.appcompat.widget.Toolbar
                android:id="@ id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </com.google.android.material.appbar.AppBarLayout>

        <include layout="@layout/content_main"
            android:id="@ id/main_container"/>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
 

Вот content_main.xml

 <androidx.constraintlayout.widget.ConstraintLayout 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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.varshakulkarni.videorecordwithlyricspoc.MainActivity"
    tools:showIn="@layout/activity_main">

    <!--This layout is created to place all the content below the AppBar without overlapping while scrolling.-->
    <FrameLayout
        android:id="@ id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true" />

    <TextView
        android:id="@ id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
<!-- Update: replace this with androidx.fragment.app.FragmentContainerView -->
    <fragment
        android:id="@ id/nav_host"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>
 

В MainActivity классе при доступе к другим представлениям, таким как текстовые представления / кнопки, мы можем использовать
binding.mainContainer.textView.text = "test" , который работает хорошо.

но как нам получить доступ androidx.navigation.fragment.NavHostFragment ?

Поскольку фрагменты не являются обычными представлениями, появляется эта ошибка: «Не удается получить доступ к ‘android.widget.fragment’. Проверьте путь к классу вашего модуля на наличие отсутствующих или конфликтующих зависимостей »

MainActivity.kt

  binding.apply {
            //Works
            mainContainer.textView.text = "test"
            //throws "Cannot access 'android.widget.fragment'. Check your module classpath for missing or conflicting dependencies"
            mainContainer.navHost.postDelayed({
                binding.mainContainer.navHost.systemUiVisibility = FLAGS_FULLSCREEN
            }, IMMERSIVE_FLAG_TIMEOUT)
        }
 

Обновление: это работает, когда FragmentContainerView используется.

Комментарии:

1. с какой целью вы хотите получить доступ к androidx.navigation. фрагмент. NavHostFragment? вы можете получить к нему доступ по его идентификатору id»nav_host»

Ответ №1:

Для размещения navGraph следует использовать FragmentContainerView вместо Fragment с атрибутом name, установленным в :

 android:name="androidx.navigation.fragment.NavHostFragment"
 

Комментарии:

1. Да, я это сделал, это было исправлено. Я должен был написать в нем ответ. Я обновил сам вопрос!