How can I include a Bottom Navigation Bar on my application without having to copy over the code to all the activities?

Viewed 93

Is there a better way to include a bottom nav on all the pages of my android application without having to copy this code to each of my activities? I think inheritance can be used but I am not too sure how to inherit and use a navigation class in Kotlin.

For my layout files, I include them currently by doing this:

<include
    android:id="@+id/include"
    layout="@layout/bottom_app_bar"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="0dp" />

The implementation code that I need to include in all my Activity files:

var bottomNavigationView = findViewById<NavigationBarView>(R.id.bottomNavigationView)
    bottomNavigationView.setOnItemSelectedListener {
        when (it.itemId) {
            R.id.miHome -> {
                val navIntent = Intent(this, MainActivity::class.java)
                startActivity(navIntent)
                true
            }
            R.id.miAccount -> {
                val navIntent = Intent(this, AccountActivity::class.java)
                startActivity(navIntent)
                true
            }
            else -> false
        }
    }
1 Answers

I recommend you to use fragments instead-but if you want to use inheritance as you have to use activities, the code below helps you understand the concept.

BottomNavActivity.kt

open class BottomNavActivity : AppCompatActivity() {

override fun setContentView(layoutResID: Int) {
    setContentView(LayoutInflater.from(this).inflate(layoutResID, null, false))
}

override fun setContentView(view: View?) {
    super.setContentView(view)
    if (view is RelativeLayout) {
        view.also {
            val bottomNav =
                LayoutInflater.from(this).inflate(R.layout.bottom_nav, null, false)
            bottomNav.layoutParams = RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            ).apply {
                addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
            }
            it.addView(bottomNav)
        }
    }
}
}

Now, extend your class like: class MainActivity : BottomNavActivity()

Related