public class

DataBindingUtil

extends java.lang.Object

 java.lang.Object

↳androidx.databinding.DataBindingUtil

Gradle dependencies

compile group: 'androidx.databinding', name: 'databinding-runtime', version: '8.8.0-alpha01'

  • groupId: androidx.databinding
  • artifactId: databinding-runtime
  • version: 8.8.0-alpha01

Artifact androidx.databinding:databinding-runtime:8.8.0-alpha01 it located at Google repository (https://maven.google.com/)

Androidx class mapping:

androidx.databinding.DataBindingUtil android.databinding.DataBindingUtil

Overview

Utility class to create ViewDataBinding from layouts.

Summary

Methods
public static ViewDataBindingbind(View root)

Returns the binding for the given layout root or creates a binding if one does not exist.

public static ViewDataBindingbind(View root, DataBindingComponent bindingComponent)

Returns the binding for the given layout root or creates a binding if one does not exist.

public static java.lang.StringconvertBrIdToString(int id)

Converts the given BR id to its string representation which might be useful for logging purposes.

public static ViewDataBindingfindBinding(View view)

Retrieves the binding responsible for the given View.

public static ViewDataBindinggetBinding(View view)

Retrieves the binding responsible for the given View layout root.

public static DataBindingComponentgetDefaultComponent()

Returns the default DataBindingComponent used in data binding.

public static ViewDataBindinginflate(LayoutInflater inflater, int layoutId, ViewGroup parent, boolean attachToParent)

Inflates a binding layout and returns the newly-created binding for that layout.

public static ViewDataBindinginflate(LayoutInflater inflater, int layoutId, ViewGroup parent, boolean attachToParent, DataBindingComponent bindingComponent)

Inflates a binding layout and returns the newly-created binding for that layout.

public static ViewDataBindingsetContentView(Activity activity, int layoutId)

Set the Activity's content view to the given layout and return the associated binding.

public static ViewDataBindingsetContentView(Activity activity, int layoutId, DataBindingComponent bindingComponent)

Set the Activity's content view to the given layout and return the associated binding.

public static voidsetDefaultComponent(DataBindingComponent bindingComponent)

Set the default DataBindingComponent to use for data binding.

from java.lang.Objectclone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Methods

public static void setDefaultComponent(DataBindingComponent bindingComponent)

Set the default DataBindingComponent to use for data binding.

bindingComponent may be passed as the first parameter of binding adapters.

When instance method BindingAdapters are used, the class instance for the binding adapter is retrieved from the DataBindingComponent.

Parameters:

bindingComponent: The default binding component to use

public static DataBindingComponent getDefaultComponent()

Returns the default DataBindingComponent used in data binding. This can be null if no default was set in DataBindingUtil.setDefaultComponent(DataBindingComponent).

Returns:

the default DataBindingComponent used in data binding. This can be null if no default was set in DataBindingUtil.setDefaultComponent(DataBindingComponent).

public static ViewDataBinding inflate(LayoutInflater inflater, int layoutId, ViewGroup parent, boolean attachToParent)

Inflates a binding layout and returns the newly-created binding for that layout. This uses the DataBindingComponent set in DataBindingUtil.setDefaultComponent(DataBindingComponent).

Use this version only if layoutId is unknown in advance. Otherwise, use the generated Binding's inflate method to ensure type-safe inflation.

Parameters:

inflater: The LayoutInflater used to inflate the binding layout.
layoutId: The layout resource ID of the layout to inflate.
parent: Optional view to be the parent of the generated hierarchy (if attachToParent is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToParent is false.)
attachToParent: Whether the inflated hierarchy should be attached to the parent parameter. If false, parent is only used to create the correct subclass of LayoutParams for the root view in the XML.

Returns:

The newly-created binding for the inflated layout or null if the layoutId wasn't for a binding layout.

See also: DataBindingUtil.setDefaultComponent(DataBindingComponent)

public static ViewDataBinding inflate(LayoutInflater inflater, int layoutId, ViewGroup parent, boolean attachToParent, DataBindingComponent bindingComponent)

Inflates a binding layout and returns the newly-created binding for that layout.

Use this version only if layoutId is unknown in advance. Otherwise, use the generated Binding's inflate method to ensure type-safe inflation.

Parameters:

inflater: The LayoutInflater used to inflate the binding layout.
layoutId: The layout resource ID of the layout to inflate.
parent: Optional view to be the parent of the generated hierarchy (if attachToParent is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToParent is false.)
attachToParent: Whether the inflated hierarchy should be attached to the parent parameter. If false, parent is only used to create the correct subclass of LayoutParams for the root view in the XML.
bindingComponent: The DataBindingComponent to use in the binding.

Returns:

The newly-created binding for the inflated layout or null if the layoutId wasn't for a binding layout.

public static ViewDataBinding bind(View root)

Returns the binding for the given layout root or creates a binding if one does not exist. This uses the DataBindingComponent set in DataBindingUtil.setDefaultComponent(DataBindingComponent).

Prefer using the generated Binding's bind method to ensure type-safe inflation when it is known that root has not yet been bound.

Parameters:

root: The root View of the inflated binding layout.

Returns:

A ViewDataBinding for the given root View. If one already exists, the existing one will be returned.

See also: DataBindingUtil.getBinding(View)

public static ViewDataBinding bind(View root, DataBindingComponent bindingComponent)

Returns the binding for the given layout root or creates a binding if one does not exist.

Prefer using the generated Binding's bind method to ensure type-safe inflation when it is known that root has not yet been bound.

Parameters:

root: The root View of the inflated binding layout.
bindingComponent: The DataBindingComponent to use in data binding.

Returns:

A ViewDataBinding for the given root View. If one already exists, the existing one will be returned.

See also: DataBindingUtil.getBinding(View)

public static ViewDataBinding findBinding(View view)

Retrieves the binding responsible for the given View. If view is not a binding layout root, its parents will be searched for the binding. If there is no binding, null will be returned.

This differs from DataBindingUtil.getBinding(View) in that findBinding takes any view in the layout and searches for the binding associated with the root. getBinding takes only the root view.

Parameters:

view: A View in the bound layout.

Returns:

The ViewDataBinding associated with the given view or null if view is not part of a bound layout.

public static ViewDataBinding getBinding(View view)

Retrieves the binding responsible for the given View layout root. If there is no binding, null will be returned. This uses the DataBindingComponent set in DataBindingUtil.setDefaultComponent(DataBindingComponent).

Parameters:

view: The root View in the layout with binding.

Returns:

The ViewDataBinding associated with the given view or null if either the view is not a root View for a layout or view hasn't been bound.

public static ViewDataBinding setContentView(Activity activity, int layoutId)

Set the Activity's content view to the given layout and return the associated binding. The given layout resource must not be a merge layout.

Parameters:

activity: The Activity whose content View should change.
layoutId: The resource ID of the layout to be inflated, bound, and set as the Activity's content.

Returns:

The binding associated with the inflated content view or null if the layoutId is not a data binding layout.

public static ViewDataBinding setContentView(Activity activity, int layoutId, DataBindingComponent bindingComponent)

Set the Activity's content view to the given layout and return the associated binding. The given layout resource must not be a merge layout.

Parameters:

bindingComponent: The DataBindingComponent to use in data binding.
activity: The Activity whose content View should change.
layoutId: The resource ID of the layout to be inflated, bound, and set as the Activity's content.

Returns:

The binding associated with the inflated content view or null if the layoutId is not a data binding layout.

public static java.lang.String convertBrIdToString(int id)

Converts the given BR id to its string representation which might be useful for logging purposes.

Parameters:

id: The integer id, which should be a field from BR class.

Returns:

The name if the BR id or null if id is out of bounds.

Source

/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package androidx.databinding;

import android.app.Activity;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

/**
 * Utility class to create {@link ViewDataBinding} from layouts.
 */
public class DataBindingUtil {
    private static DataBinderMapper sMapper = new DataBinderMapperImpl();
    private static DataBindingComponent sDefaultComponent = null;

    /**
     * Prevent DataBindingUtil from being instantiated.
     */
    private DataBindingUtil() {}

    /**
     * Set the default {@link DataBindingComponent} to use for data binding.
     * <p>
     * <code>bindingComponent</code> may be passed as the first parameter of binding adapters.
     * <p>
     * When instance method BindingAdapters are used, the class instance for the binding adapter
     * is retrieved from the DataBindingComponent.
     *
     * @param bindingComponent The default binding component to use
     */
    public static void setDefaultComponent(@Nullable DataBindingComponent bindingComponent) {
        sDefaultComponent = bindingComponent;
    }

    /**
     * Returns the default {@link DataBindingComponent} used in data binding. This can be
     * <code>null</code> if no default was set in
     * {@link #setDefaultComponent(DataBindingComponent)}.
     *
     * @return the default {@link DataBindingComponent} used in data binding. This can be
     * <code>null</code> if no default was set in
     * {@link #setDefaultComponent(DataBindingComponent)}.
     */
    @Nullable
    public static DataBindingComponent getDefaultComponent() {
        return sDefaultComponent;
    }

    /**
     * Inflates a binding layout and returns the newly-created binding for that layout.
     * This uses the DataBindingComponent set in
     * {@link #setDefaultComponent(DataBindingComponent)}.
     * <p>
     * Use this version only if <code>layoutId</code> is unknown in advance. Otherwise, use
     * the generated Binding's inflate method to ensure type-safe inflation.
     *
     * @param <T> Type of the generated binding class.
     * @param inflater The LayoutInflater used to inflate the binding layout.
     * @param layoutId The layout resource ID of the layout to inflate.
     * @param parent Optional view to be the parent of the generated hierarchy
     *               (if attachToParent is true), or else simply an object that provides
     *               a set of LayoutParams values for root of the returned hierarchy
     *               (if attachToParent is false.)
     * @param attachToParent Whether the inflated hierarchy should be attached to the
     *                       parent parameter. If false, parent is only used to create
     *                       the correct subclass of LayoutParams for the root view in the XML.
     * @return The newly-created binding for the inflated layout or <code>null</code> if
     * the layoutId wasn't for a binding layout.
     * @throws InflateException When a merge layout was used and attachToParent was false.
     * @see #setDefaultComponent(DataBindingComponent)
     */
    // @Nullable don't annotate with Nullable. It is unlikely to be null and makes using it from
    // kotlin really ugly. We cannot make it NonNull w/o breaking backward compatibility.
    public static <T extends ViewDataBinding> T inflate(@NonNull LayoutInflater inflater,
            int layoutId, @Nullable ViewGroup parent, boolean attachToParent) {
        return inflate(inflater, layoutId, parent, attachToParent, sDefaultComponent);
    }

    /**
     * Inflates a binding layout and returns the newly-created binding for that layout.
     * <p>
     * Use this version only if <code>layoutId</code> is unknown in advance. Otherwise, use
     * the generated Binding's inflate method to ensure type-safe inflation.
     *
     * @param <T> Type of the generated binding class.
     * @param inflater The LayoutInflater used to inflate the binding layout.
     * @param layoutId The layout resource ID of the layout to inflate.
     * @param parent Optional view to be the parent of the generated hierarchy
     *               (if attachToParent is true), or else simply an object that provides
     *               a set of LayoutParams values for root of the returned hierarchy
     *               (if attachToParent is false.)
     * @param attachToParent Whether the inflated hierarchy should be attached to the
     *                       parent parameter. If false, parent is only used to create
     *                       the correct subclass of LayoutParams for the root view in the XML.
     * @param bindingComponent The DataBindingComponent to use in the binding.
     * @return The newly-created binding for the inflated layout or <code>null</code> if
     * the layoutId wasn't for a binding layout.
     * @throws InflateException When a merge layout was used and attachToParent was false.
     */
    // @Nullable don't annotate with Nullable. It is unlikely to be null and makes using it from
    // kotlin really ugly. We cannot make it NonNull w/o breaking backward compatibility.
    public static <T extends ViewDataBinding> T inflate(
            @NonNull LayoutInflater inflater, int layoutId, @Nullable ViewGroup parent,
            boolean attachToParent, @Nullable DataBindingComponent bindingComponent) {
        final boolean useChildren = parent != null && attachToParent;
        final int startChildren = useChildren ? parent.getChildCount() : 0;
        final View view = inflater.inflate(layoutId, parent, attachToParent);
        if (useChildren) {
            return bindToAddedViews(bindingComponent, parent, startChildren, layoutId);
        } else {
            return bind(bindingComponent, view, layoutId);
        }
    }

    /**
     * Returns the binding for the given layout root or creates a binding if one
     * does not exist. This uses the DataBindingComponent set in
     * {@link #setDefaultComponent(DataBindingComponent)}.
     * <p>
     * Prefer using the generated Binding's <code>bind</code> method to ensure type-safe inflation
     * when it is known that <code>root</code> has not yet been bound.
     *
     * @param <T> Type of the generated binding class.
     * @param root The root View of the inflated binding layout.
     * @return A ViewDataBinding for the given root View. If one already exists, the
     * existing one will be returned.
     * @throws IllegalArgumentException when root is not from an inflated binding layout.
     * @see #getBinding(View)
     */
    @SuppressWarnings("unchecked")
    @Nullable
    public static <T extends ViewDataBinding> T bind(@NonNull View root) {
        return bind(root, sDefaultComponent);
    }

    /**
     * Returns the binding for the given layout root or creates a binding if one
     * does not exist.
     * <p>
     * Prefer using the generated Binding's <code>bind</code> method to ensure type-safe inflation
     * when it is known that <code>root</code> has not yet been bound.
     *
     * @param <T> Type of the generated binding class.
     * @param root The root View of the inflated binding layout.
     * @param bindingComponent The DataBindingComponent to use in data binding.
     * @return A ViewDataBinding for the given root View. If one already exists, the
     * existing one will be returned.
     * @throws IllegalArgumentException when root is not from an inflated binding layout.
     * @see #getBinding(View)
     */
    @SuppressWarnings("unchecked")
    @Nullable
    public static <T extends ViewDataBinding> T bind(@NonNull View root,
            DataBindingComponent bindingComponent) {
        T binding = getBinding(root);
        if (binding != null) {
            return binding;
        }
        Object tagObj = root.getTag();
        if (!(tagObj instanceof String)) {
            throw new IllegalArgumentException("View is not a binding layout");
        } else {
            String tag = (String) tagObj;
            int layoutId = sMapper.getLayoutId(tag);
            if (layoutId == 0) {
                throw new IllegalArgumentException("View is not a binding layout. Tag: " + tagObj);
            }
            return (T) sMapper.getDataBinder(bindingComponent, root, layoutId);
        }
    }

    @SuppressWarnings("unchecked")
    static <T extends ViewDataBinding> T bind(DataBindingComponent bindingComponent, View[] roots,
            int layoutId) {
        return (T) sMapper.getDataBinder(bindingComponent, roots, layoutId);
    }

    static <T extends ViewDataBinding> T bind(DataBindingComponent bindingComponent, View root,
            int layoutId) {
        return (T) sMapper.getDataBinder(bindingComponent, root, layoutId);
    }

    /**
     * Retrieves the binding responsible for the given View. If <code>view</code> is not a
     * binding layout root, its parents will be searched for the binding. If there is no binding,
     * <code>null</code> will be returned.
     * <p>
     * This differs from {@link #getBinding(View)} in that findBinding takes any view in the
     * layout and searches for the binding associated with the root. <code>getBinding</code>
     * takes only the root view.
     *
     * @param <T> Type of the generated binding class.
     * @param view A <code>View</code> in the bound layout.
     * @return The ViewDataBinding associated with the given view or <code>null</code> if
     * view is not part of a bound layout.
     */
    @Nullable
    public static <T extends ViewDataBinding> T findBinding(@NonNull View view) {
        while (view != null) {
            ViewDataBinding binding = ViewDataBinding.getBinding(view);
            if (binding != null) {
                return (T) binding;
            }
            Object tag = view.getTag();
            if (tag instanceof String) {
                String tagString = (String) tag;
                if (tagString.startsWith("layout") && tagString.endsWith("_0")) {
                    final char nextChar = tagString.charAt(6);
                    final int slashIndex = tagString.indexOf('/', 7);
                    boolean isUnboundRoot = false;
                    if (nextChar == '/') {
                        // only one slash should exist
                        isUnboundRoot = slashIndex == -1;
                    } else if (nextChar == '-' && slashIndex != -1) {
                        int nextSlashIndex = tagString.indexOf('/', slashIndex + 1);
                        // only one slash should exist
                        isUnboundRoot = nextSlashIndex == -1;
                    }
                    if (isUnboundRoot) {
                        // An inflated, but unbound layout
                        return null;
                    }
                }
            }
            ViewParent viewParent = view.getParent();
            if (viewParent instanceof View) {
                view = (View) viewParent;
            } else {
                view = null;
            }
        }
        return null;
    }

    /**
     * Retrieves the binding responsible for the given View layout root. If there is no binding,
     * <code>null</code> will be returned. This uses the DataBindingComponent set in
     * {@link #setDefaultComponent(DataBindingComponent)}.
     *
     * @param <T> Type of the generated binding class.
     * @param view The root <code>View</code> in the layout with binding.
     * @return The ViewDataBinding associated with the given view or <code>null</code> if
     * either the view is not a root View for a layout or view hasn't been bound.
     */
    @Nullable
    public static <T extends ViewDataBinding> T getBinding(@NonNull View view) {
        return (T) ViewDataBinding.getBinding(view);
    }

    /**
     * Set the Activity's content view to the given layout and return the associated binding.
     * The given layout resource must not be a merge layout.
     *
     * @param <T> Type of the generated binding class.
     * @param activity The Activity whose content View should change.
     * @param layoutId The resource ID of the layout to be inflated, bound, and set as the
     *                 Activity's content.
     * @return The binding associated with the inflated content view or {@code null} if the
     * layoutId is not a data binding layout.
     */
    // @Nullable don't annotate with Nullable. It is unlikely to be null and makes using it from
    // kotlin really ugly. We cannot make it NonNull w/o breaking backward compatibility.
    public static <T extends ViewDataBinding> T setContentView(@NonNull Activity activity,
            int layoutId) {
        return setContentView(activity, layoutId, sDefaultComponent);
    }

    /**
     * Set the Activity's content view to the given layout and return the associated binding.
     * The given layout resource must not be a merge layout.
     *
     * @param <T> Type of the generated binding class.
     * @param bindingComponent The DataBindingComponent to use in data binding.
     * @param activity The Activity whose content View should change.
     * @param layoutId The resource ID of the layout to be inflated, bound, and set as the
     *                 Activity's content.
     * @return The binding associated with the inflated content view or {@code null} if the
     * layoutId is not a data binding layout.
     */
    // @Nullable don't annotate with Nullable. It is unlikely to be null and makes using it from
    // kotlin really ugly. We cannot make it NonNull w/o breaking backward compatibility.
    public static <T extends ViewDataBinding> T setContentView(@NonNull Activity activity,
            int layoutId, @Nullable DataBindingComponent bindingComponent) {
        activity.setContentView(layoutId);
        View decorView = activity.getWindow().getDecorView();
        ViewGroup contentView = (ViewGroup) decorView.findViewById(android.R.id.content);
        return bindToAddedViews(bindingComponent, contentView, 0, layoutId);
    }

    /**
     * Converts the given BR id to its string representation which might be useful for logging
     * purposes.
     *
     * @param id The integer id, which should be a field from BR class.
     * @return The name if the BR id or {@code null} if id is out of bounds.
     */
    @Nullable
    public static String convertBrIdToString(int id) {
        return sMapper.convertBrIdToString(id);
    }

    private static <T extends ViewDataBinding> T bindToAddedViews(DataBindingComponent component,
            ViewGroup parent, int startChildren, int layoutId) {
        final int endChildren = parent.getChildCount();
        final int childrenAdded = endChildren - startChildren;
        if (childrenAdded == 1) {
            final View childView = parent.getChildAt(endChildren - 1);
            return bind(component, childView, layoutId);
        } else {
            final View[] children = new View[childrenAdded];
            for (int i = 0; i < childrenAdded; i++) {
                children[i] = parent.getChildAt(i + startChildren);
            }
            return bind(component, children, layoutId);
        }
    }
}