绑定适配器在Android中有什么用? [英] What is the use of binding adapter in Android?

查看:105
本文介绍了绑定适配器在Android中有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读有关Android中的绑定适配器的文章,但我似乎不太了解. 什么时候使用绑定适配器? 有人可以用一个简单的例子来解释吗?

I have been reading articles about binding adapter in Android, but I don't seem to understand it. When is a binding adapter used? Can someone explain it with a simple example?

我读过的一篇文章在主活动中有一个绑定适配器.绑定适配器具有一个参数"toastMessage",并且显然,只要"toastMessage"(在viewModel类中是一个属性)发生更改,便会调用此绑定适配器注释的方法.

An article I read had a binding adapter in the Main Activity. The binding Adapter had a parameter "toastMessage", and apparently, the method annotated with this binding adapter was said to be called whenever the "toastMessage" (which was an attribute in viewModel class) changed.

我不明白为什么我们需要这样做.

I don't understand why we need to do this.

用一个简单的例子进行解释会很有帮助.

An explanation with a simple example would help a lot.

谢谢!

推荐答案

绑定适配器用于为视图的某些属性提供自定义设置器.我能想到的最常见的用例是将图像设置为ImageView,其中图像的加载大部分是通过UI线程完成的.

Binding Adapters are used to have custom setters to some property of your views. The most common use case I can think of is setting an image to an ImageView, where loading of image is mostly done off the UI thread.

我们大多数人都有我们首选的图像加载库来加载图像.对于您要加载的每个图像,您将编写代码以从远程(或本地)加载url并将其设置为我们的图像视图.一旦在有图像视图的每个位置看到样板,您当然可以使用一些实用方法.

Most of us have our preferred image loading library to load images. For every image you would want to load you would write code to load the url from remote (or local) and set it to our image view. You could of course have some utility method once you see this boilerplate in every place you have an image view.

绑定适配器使此操作更加简单.您在XML中设置属性,数据绑定库将查找绑定适配器以将该属性设置为您的视图.由于数据是可观察的,因此每当数据更改时,都会触发视图更改.

Binding adapters makes this a little more simpler. You set the attribute in XML and data binding library will look for the binding adapter to set that property to your view. Since the data is an observable changes will be triggered to the view whenever the data changes.

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:imageUrl="@{data.imageUrl}"/>

@BindingAdapter("imageUrl")
public static void setImageUrl(ImageView imageView, String url) {
    if (url == null) {
        imageView.setImageDrawable(null);
    } else {
        Picasso.get().load(url).into(imageView); // replace with your fav image loading lib
    }
}

文档提供了一些这样的示例,您可以在其中想要使用这个.乔治·芒特(George Mount)的文章也非常清楚地说明了在何处以及如果使用数据绑定,为什么可能要使用此功能.

The doc provides several such examples where you would want to use this. This article by George Mount also explains it very clearly where and why you may want to use this if you are using data binding.

这篇关于绑定适配器在Android中有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆