Hello all, this is my first post in kotlin discussion forum
I want to know that we can use UI element directly calling it’s id using kotlin extensions, same can be done with binding libraries even though to bind we have to write couple lines of code but I found kotlin easier for calling id’s directly ? So how binding libraries are different ? What other things can those libraries do that kotlin doesn’t ? Can I use both together ?
Thank you
It’s a little unclear what you’re asking for. Could you provide a code example of the differences you’re describing?
Android Data Binding auto-generates Java classes with getters for each View
with an ID. If you have some view layout like:
<!-- some_layout.xml -->
<layout>
<FrameLayout android:layout_height="wrap_content"
android:layout_width="wrap_content">
<View android:id="@+id/some_view"
android:layout_height="10dp"
android:layout_width="10dp" />
</FrameLayout>
</layout>
You could access @+id/some_view
via the syntax (Java):
// SomeActivity.java
@Override
public void onCreate(Bundle savedInstanceState) {
SomeLayoutBinding binding = DataBindingUtil.setContentView(this, R.layout.some_layout);
View someView = binding.getSomeView();
}
Kotlin has a language feature that will treat Java getters/setters like a property, so getting the same view from Kotlin would look like:
// SomeActivity.kt
override fun onCreate(bundle: SavedInstanceState?) {
val binding: SomeLayoutBinding = DataBindingUtil.setContentView(this, R.layout.some_layout)
val someView: View = binding.someView
}
These two Activity code snippets are identical in functionality. I won’t claim to know whether they compile to the same bytecode, but there are no semantic differences between the Java and Kotlin here.
Not sure if this is exactly what you are asking but here it s an article on the right way to use kotlin android extensions with Android view binding: