Android中的BindingAdapter

问题描述 投票:0回答:2

我正在关注有关RecyclerView和数据绑定的course

我已经读过What is the use of binding adapter in Android?

[make custom/more complex setter以外,相比[normal]方式使用BindingAdapter有什么好处?表现有所提高吗?

Version1:

  • xml:

     <TextView
        android:id="@+id/sleep_length"
        android:layout_width="0dp"
        android:layout_height="20dp"
        ...
        tools:text="Wednesday" />
    
  • 适配器

    fun bind(item: SleepNight) {
        val res = itemView.context.resources
        sleepLength.text = convertDurationToFormatted(item.startTimeMilli, item.endTimeMilli, res)
    }
    

Version2(DataBinding):

  • xml:

    <TextView
        android:id="@+id/sleep_length"
        android:layout_width="0dp"
        android:layout_height="20dp"
        app:sleepDurationFormatted="@{sleep}"
        ...
        tools:text="Wednesday" />
    
  • 适配器

    fun bind(item: SleepNight) {
        binding.sleep = item
    }
    
  • BindingUtils:

    @BindingAdapter("sleepDurationFormatted")
    fun TextView.setSleepDurationFormatted(item: SleepNight){
           text = convertDurationToFormatted(item.startTimeMilli, item.endTimeMilli, context.resources)
    }
    
android kotlin android-databinding android-binding-adapter
2个回答
0
投票

绑定适配器为您提供了一个很好的自定义视图功能。看起来很奇怪!

First,假设您有一个显示国家国旗的ImageView。

接受:国家/地区代码(字符串)

操作:显示国家/地区的标志,如果国家/地区代码为null,则使ImageView为GONE。

@BindingAdapter({"android:setFlag"})
public static void setFlagImageView(ImageView imageView, String currencyCode) {
    Context context = imageView.getContext();
    if (currencyCode != null) {
        try {
            Drawable d = Drawable.createFromStream(context.getAssets().open("flags/"+currencyCode.toLowerCase()+".png"), null);
            imageView.setImageDrawable(d);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    else{
            imageView.setVisibility(View.GONE);
    }
}

所以现在您可以在其他任何地方重用此BindinAdapter。

热爱DataBinding的人们,他们可以减少代码量并在xml中编写一些逻辑。而不是辅助方法。

第二,通过数据绑定,您将忽略findViewById,因为将为您创建一个生成的文件。

关于性能,我在官方文档中找不到任何表明BindingAdapter可以提高性能的信息。


0
投票

甚至都不认识我Assam Career

@@ BindingAdapter({“ android:setFlag”})] >>

© www.soinside.com 2019 - 2024. All rights reserved.