MakeTheErrorDie
MakeTheErrorDie

Reputation: 127

Using bottom navigation - Android Studio

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'

Upvotes: 0

Views: 132

Answers (2)

Saikiran Kopparthi
Saikiran Kopparthi

Reputation: 52

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()
 }

Upvotes: 1

Aasima Jamal
Aasima Jamal

Reputation: 119

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

Upvotes: 0

Related Questions