I was following this tutorial.
Which was about using the bottom navigation bar.
This below part is the code from the MainActivity file:
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val firstFragment=FirstFragment()
val secondFragment=SecondFragment()
val thirdFragment=ThirdFragment()
setCurrentFragment(firstFragment)
bottomNavigationView.setOnNavigationItemSelectedListener {
when(it.itemId){
R.id.home->setCurrentFragment(firstFragment)
R.id.person->setCurrentFragment(secondFragment)
R.id.settings->setCurrentFragment(thirdFragment)
}
true
}
}
private fun setCurrentFragment(fragment:Fragment)=
supportFragmentManager.beginTransaction().apply {
replace(R.id.flFragment,fragment) #HERE
commit()
}
}
I got an exception of the argument when calling replace() in setCurrentFragment. ‘flFragment’ is the argument passed in the tutorial, but I’m not sure what I should pass there.
When I tried to pass a Fragment view id, the R.id. did not find the fragment id views.
When building it returns the error, ‘x argument should be a View etc’
2
Answers
As per your Example, the id of "flFragment is used as an id of the "FrameLayout" in mainActivity xml. Do check there.
The error is caused because of the Null Pointer Exception since you are not passing the correct
id
of the FrameLayout. Follow the below steps to solve your issue.Before once check whether you have binded the bottomNav to your Kotlin file
bottomNav = findViewById(R.id.bottomNav)
Navigate to your MainActivity.xml or where you have initialised the FrameLayout. Here in my case
Now in your Kotlin Code, MainActivity.kt.Here, we need to pass the
id
of theFramelayout
here in my case