skip to Main Content

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


  1. As per your Example, the id of "flFragment is used as an id of the "FrameLayout" in mainActivity xml. Do check there.

    Login or Signup to reply.
  2. 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

      <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:id="@+id/fragmentContainer"
            app:layout_constraintTop_toTopOf="parent" />
    

    Now in your Kotlin Code, MainActivity.kt.Here, we need to pass the id of the Framelayout here in my case

    // This method is used to replace Fragment
     private fun setCurrentFragment(fragment : Fragment){
       val transaction = supportFragmentManager.beginTransaction()
       transaction.replace(R.id.fragmentContainer,fragment)
       transaction.commit()
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search