After enabling viewbinding using:
android {
...
buildFeatures {
viewBinding = true
}
}
We can use ViewBinding, the problem is that we need to use binding.
prefix before accesing each view. Is there a way we can ommit this prefix, and have direct access of the views from the class?
So instead of:
binding.textview1.text = viewModel.name
binding.button1.setOnClickListener { viewModel.userClicked() }
To use directly:
textview1.text = viewModel.name
button1.setOnClickListener { viewModel.userClicked() }
Obviously we can use with(binding)
and use with each method, but is there a way to apply this for the whole class globally?
fun method = with(binding){
// now we can access the viewbinding
textview1.text = viewModel.name
button1.setOnClickListener { viewModel.userClicked() }
}
Are there any binding settings, were we can specify for the compiler to generate the Interface from the layout:
So it will auto gnerate:
public interface Fragment1BindingInterface {
@NonNull
TextView getTextView1();
}
public final class Fragment1Binding implements ViewBinding, Fragment1BindingInterface {
@NonNull
private final RelativeLayout rootView;
@Override
@NonNull
private final TextView _textView1;
@Override
@NonNull
public TextView getTextView1() {
return _textView1;
}
}
Then we can implement Fragment1BindingInterface, in out fragment class and have direct access to all views, without using binding.
every time. Although this will expose the views publicly, but anyway just asking if it is possible or not?
It's probably not what you are looking for but maybe you think it's an improvement anyway, and that is to list all views that you want at the top of your class like
and then you can use them just like that as you want inside of the class.