Kotlin newbie here;
I'm working my way through a tutorial, https://developer.android.com/guide/topics/ui/floating-action-button
I see in a the basic activity sample code a findViewById<FloatingActionButton>(R.id.fab)
, where the <FloatingActionButton>
part is throwing me off.
findViewById<FloatingActionButton>(R.id.fab).setOnClickListener { view ->
Snackbar.make(view, getString(R.string.MySnackBar), Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
I'm confused because in other sample code, i see
val rollButton: Button = findViewById(R.id.roll_button)
Is the first findViewById<FloatingActionButton>
an interface(?) And if so, why does it need one, when the second one works by passing it in a button as is?
Am I misunderstanding syntax, or missing a concept perhaps?
I'm sure I'm missing some piece of this puzzle, but don't see it.
Thanks preemptively for any help or doc you can refer me to that explains it!
findViewById()
needs to be told what type of view to expect. You can do this in one of two ways:
val button: Button = findViewById(R.id.button)
findViewById()
val button = findViewById<Button>(R.id.button)
You can of course combine the two, but only one is necessary.
Personally, I prefer the first option because it avoids the inferring of platform types.