Solution 1 :
Functionality wise, both the snippets are the same.
Snippet 1 is using a lambda expression for setOnItemSelectedListener whereas the Snippet 2 uses a singleton object implementing the interface ChipNavigationBar.OnItemSelectedListener.
To simply your code, you should use a lambda expression.
Also, you can use lambda expression only if your interface has only 1 function that’s need to overridden.
Problem :
I have the following code snippets
Please help me figure out the difference between the same
Snippet 1
navbar.setOnItemSelectedListener { id ->
var fragment: Fragment? = null
when (id) {
R.id.home -> fragment = HomeFragment()
R.id.graphical_stats -> fragment = GraphicalStats()
R.id.sources -> fragment = SourcesFragment()
}
if (fragment != null) {
supportFragmentManager.beginTransaction().replace(R.id.container_frame, fragment)
.commit()
} else {
Log.e(TAG, "Error Creating Fragment")
}
}
Snippet 2
navbar.setOnItemSelectedListener { object : ChipNavigationBar.OnItemSelectedListener{
override fun onItemSelected(id: Int) {
var fragment: Fragment? = null
when (id) {
R.id.home -> fragment = HomeFragment()
R.id.graphical_stats -> fragment = GraphicalStats()
R.id.sources -> fragment = SourcesFragment()
}
if (fragment != null) {
supportFragmentManager.beginTransaction().replace(R.id.container_frame, fragment)
.commit()
} else {
Log.e(TAG, "Error Creating Fragment")
}
}
I am using ChipNavigationBar and have three fragments namely Home Graphical Stats and Sources which will be created or swapped accordingly
Comments
Comment posted by gtxtreme
Actually I tried the second one but it doesn’t seem to work Only the first one worked any idea why?
Comment posted by Alpha 1
Because you have added { before setOnItemSelectedListener it should be a normal bracket ( . it should be like this :