Here are a few examples of how Android KTX can make your Kotlin code more concise:
- Instead of calling
findViewById
to get a reference to a view in your layout, you can use thesynthetic
property to access the view directly. For example:
// Before (Java) TextView textView = findViewById(R.id.text_view);
// After (Kotlin) val textView = text_view
- You can use the
apply
function to initialize an object and set its properties in a single statement. For example:
// Before (Java)
TextView textView = new TextView(context);
textView.setText("Hello, World!");
textView.setTextColor(Color.BLACK);
// After (Kotlin)
val textView = TextView(context).apply {
text = "Hello, World!" textColor = Color.BLACK
}
- You can use the
also
function to perform an action on an object after it has been initialized. For example:
// Before (Java)
TextView textView = new TextView(context);
textView.setText("Hello, World!");
textView.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) { // Do something }
});
// After (Kotlin)
val textView = TextView(context).also {
it.text = "Hello, World!" it.setOnClickListener { // Do something }
}