I want to establish a relationship between a ProgressBar
and a WebView
Something like this in XML:
<ProgressBar
android:id="@+id/progressBar"/>
<WebView
android:id="@+id/wvb_webView"
app:attachedProgressBar="@{@id/progressBar}"/>
With this code I can create a BindingAdapter
to do the wiring like this:
@BindingAdapter({"app:attachedProgressBar"})
public static void setAttachedProgressBar(WebView webView, @IdRes int progressBarId) {
ProgressBar progBar = (ProgressBar) DataBindingUtil.getBinding(webView).getRoot().findViewById(progressBarId);
wireStuff(webView, progBar);
}
This works, but it irks me that I have to call findViewById
. Is there any way I can refactor the XML and the BindingAdapter to take a direct reference to the ProgressBar
as input instead of the @IdRes int
?
android.databinding.BindingAdapter BindingAdapter is applied to methods that are used to manipulate how values with expressions are set to views. The simplest example is to have a public static method that takes the view and the value to set:
To convert a layout into a Data Binding layout, go to the parent layout and press Option + return button, while will open a menu. From the menu presented select Convert to data binding layout and your view will be converted to a Data Binding layout. <ConstraintLayout... /> <!-- UI layout's root element -->
The one and only function of View Binding is to bind the views in the code, while Data Binding offers some more options like Binding Expressions which allows us to write expressions the connect variables to the views in the layout.
The Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically. To enable Data Binding add the following snippet in the module level build.gradle file:
Instead of id, directly pass ProgressBar
in your BindingAdapter
@BindingAdapter({"app:attachedProgressBar"})
public static void setAttachedProgressBar(WebView webView, ProgressBar progBar) {
wireStuff(webView, progBar);
}
XML code :
<ProgressBar
android:id="@+id/progressBar"/>
<WebView
android:id="@+id/wvb_webView"
app:attachedProgressBar="@{progressBar}"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With