0

我正在学习这关于 RecyclerView 和数据绑定的课程。

我已阅读Android 中绑定适配器的用途是什么?.

除了制作自定义/更复杂的设置器BindingAdapter之外,使用“正常”方式有什么好处?性能有提升吗?

版本1:

  • 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)
    }
    

版本 2(数据绑定):

  • 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
    }
    
  • 绑定工具:

    @BindingAdapter("sleepDurationFormatted")
    fun TextView.setSleepDurationFormatted(item: SleepNight){
           text = convertDurationToFormatted(item.startTimeMilli, item.endTimeMilli, context.resources)
    }
    
4

1 回答 1

0

Binding Adapter 为您提供了一个很好的自定义视图功能。好像很奇怪!。

首先,假设您有一个显示国旗的 ImageView。

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

行动:显示国家的国旗,如果国家代码为空,使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 可以提高性能。

于 2020-03-23T13:19:12.673 回答