Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a View as input to a data binding BindingAdapter on Android?

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 ?

like image 879
Nilzor Avatar asked Nov 03 '16 11:11

Nilzor


People also ask

What is databinding binding adapter in Android?

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:

How to convert a view to a data binding layout?

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 -->

What is the difference between view binding and data binding?

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.

How do I use the data binding library?

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:


1 Answers

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}"/> 
like image 108
Ravi Avatar answered Sep 26 '22 20:09

Ravi