Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to declare on UI component in android with Kotlin?

I'm trying to build android application using Kotlin for the first time.

I want to declare on some buttons outside the OnCreate method and i can initialize them only Inside this function with findViewById.

Can i declare in simple and clean code like in java?

private Button btnProceed;

Because when converting it to Kotlin it look like:

private var btnProceed: Button? = null

And then when initialize OnClick function need to add ! sign:

btnProceed!!.setOnClickListener

What is the right and cleanest way?

like image 536
Udi Avatar asked May 31 '17 13:05

Udi


2 Answers

Instead of using lateinit, you can also do lazy initialization:

private val button by lazy {
    findViewById(R.id.button) as Button
}

The first time you access the button property, it will execute the block once and use the result for future calls. In onCreate for example, you can now directly access it:

fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(bundle)
  setContentView(R.layout.my_view)

  button.setOnClickListener { ... }
}
like image 23
nhaarman Avatar answered Oct 24 '22 04:10

nhaarman


This is a good use case for lateinit. Marking a property lateinit allows you to make it non nullable, but not assign it a value at the time that your Activity's constructor is called. It's there precisely for classes like Activities, when initialization happens in a separate initializer method, later than the constructor being run (in this case, onCreate).

private lateinit var btnProceed: Button

If the property is read before a real value is assigned to it, it will throw an exception at runtime - by using lateinit, you're taking the responsibility for initializing it before you access it for the first time.


Otherwise, if you want the compiler to guarantee safe access for you, you can make the Button nullable as the converter does by default. Instead of the unsafe !! operator though, which the converter often uses, you should use the safe call operator where you access the property:

btnProceed?.setOnClickListener { ... }

This will make a regular call if btnProceed is a non-null value, and do nothing otherwise.


On a final note, you can check out Kotlin Android Extensions, which eliminates the need to create properties for your Views altogether, if it works for your project.


Last edit (for now): you should also look at using lazy as described in the other answers. Being lazy is cool.

like image 166
zsmb13 Avatar answered Oct 24 '22 02:10

zsmb13