Reputation: 57
I already found a solution to this. But it took quite a while and a lot of references to stumble upon so I will leave this here.
This is an app that has MVVM data binding throwing error related to Nav Controller.
fragment initially gave Duplicate id error on NavHostFrament on the data binding line in my activity. Removing either android:id or android:name gave either build error or runtime error.
Activity.kt
binding = DataBindingUtil.setContentView(this, R.layout.activity_home)
.
.
.
val navController = findNavController(R.id.nav_host_fragment)
Layout.xml
<fragment
android:id="@+id/nav_host_fragment"
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/mobile_navigation"/>
while the fragment line gave me a lint check to convert to FragmentContainerView it started throwing NavController not set error.
Upvotes: 1
Views: 753
Reputation: 1496
I had the same problem then I realized that I set the content view of the activitiy both using setContentView() method and DataBindingUtil.setContentView() method. I removed one of them and the problem is solved.
I replaced my code from:
setContentView(R.layout.activity_main)
val binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
to:
val binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
Upvotes: 0
Reputation: 57
I transferred the fragment tag to a separate xml file. Though I believe this is not needed.
nav_header.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.fragment.app.FragmentContainerView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/nav_host_fragment"
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/mobile_navigation" />
As for the Activity file. Following this link... https://issuetracker.google.com/issues/142847973#comment4
Replaced
val navController = findNavController(R.id.nav_host_fragment)
with
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
Upvotes: 3