почему мой фрагмент не отображается в контроллере навигации?

Я новичок в использовании навигационного контроллера для Android.

Вот xml моей основной деятельности:

<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".Activities.MainActivity">

    <androidx.appcompat.widget.Toolbar
            android:id="@+id/main_activity_toolbar"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            android:elevation="4dp" app:layout_constraintHorizontal_bias="0.0">
    </androidx.appcompat.widget.Toolbar>

    <fragment
            android:id="@+id/nav_main_host_fragment"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toTopOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/main_activity_toolbar"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            android:name="androidx.navigation.fragment.NavHostFragment"
            app:navGraph="@navigation/main_graph"
            app:defaultNavHost="true"
    />

</androidx.constraintlayout.widget.ConstraintLayout>

мой котлин Основная деятельность:

class MainActivity : AppCompatActivity(),NavController.OnDestinationChangedListener {
    lateinit var navController : NavController

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        navController = Navigation.findNavController(this,R.id.nav_main_host_fragment)
        navController.addOnDestinationChangedListener(this)

        setupActionBar()
    }

    override fun onDestinationChanged(
        controller: NavController,
        destination: NavDestination,
        arguments: Bundle?) {
    }

    private fun setupActionBar() {
        setSupportActionBar(main_activity_toolbar)
        supportActionBar?.title = null

        val appBarConfiguration = AppBarConfiguration(
            setOf(
                // set some destination as the top hierarchy destination
                // to make the up button doesn't show.
                R.id.destination_latestMessage
            ))

        NavigationUI.setupWithNavController(
            main_activity_toolbar,
            navController,
            appBarConfiguration)
    }
}

мой фрагмент 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"
    tools:context=".Fragments.LatestMessageFragment"
    android:id="@+id/ConstraintLayout_latestMessage">

    <!-- TODO: Update blank fragment layout -->
    <TextView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="latest message"
            android:id="@+id/textView" 
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" 
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"/>
    <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button" 
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toTopOf="parent" 
            app:layout_constraintBottom_toBottomOf="@+id/textView" 
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="@+id/textView"
            android:layout_marginStart="8dp" 
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

мой фрагмент котлинского файла:

class LatestMessageFragment : Fragment() {

    lateinit var mContext : Context
    lateinit var mActivity : FragmentActivity
    lateinit var fragmentView : View

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context
        activity?.let { mActivity = it }

    }

    override fun onCreateView(
        inflater: LayoutInflater, 
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        fragmentView = inflater.inflate(
            R.layout.fragment_latest_message, 
            container, 
            false)
        setHasOptionsMenu(true) // to setup custom menu on the action bar
        return fragmentView
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
    }

    override fun onResume() {
        super.onResume()
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.log_out_menu, menu)
        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val id = item.itemId

        return when (id) {
            R.id.logout-> {
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
}

и вот 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/main_graph"
            app:startDestination="@id/destination_latestMessage">

    <fragment android:id="@+id/destination_latestMessage" 
          android:name="com.lakuin.cs.Fragments.LatestMessageFragment"
          android:label="Latest Message"
          tools:layout="@layout/fragment_latest_message"/>
</navigation>

как вы можете видеть, в моем целевом фрагменте есть кнопка и текстовое представление, но когда я запускаю приложение, текстовое представление и кнопка не появляются на экране.

У меня есть только один фрагмент, но этот фрагмент не отображается на экране, но панель инструментов и ее меню, которое я установил, отображаются на экране

Я использую приведенную ниже зависимость:

//Navigation controller
implementation 'android.arch.navigation:navigation-fragment-ktx:1.0.0-rc02'
implementation 'android.arch.navigation:navigation-ui-ktx:1.0.0-rc02'

что здесь пошло не так?


comment
app:layout_constraintBottom_toTopOf="parent"? Это проблема?   -  person Ranjan    schedule 04.03.2019
comment
app: layout_contraintBottom_toBottomOf = родительский правильный.   -  person Hussnain Haidar    schedule 04.03.2019


Ответы (1)


Как указывает @Ranjan, это проблема макета вашего навигационного фрагмента. Это не связано с пользовательским интерфейсом навигации. Использовать:

app:layout_constraintBottom_toBottomOf="parent"

Вместо того:

app:layout_constraintBottom_toTopOf="parent"

В вашем макете NavControllerFragmnet.

person Hussnain Haidar    schedule 04.03.2019