-1

我知道 DataBinding 可以比findViewById.
此处对此进行了解释:Android 数据绑定与 findViewById 的性能

我现在想知道以下哪个选项更快:

选项 A

xml:

 <TextView
      android:id="@+id/my_text_view"/>

用法:

mBinding.myTextView.setText("DummyText")

选项 B

xml:

 <variable
     name="dummy"
     type="String" />

 ...
 <TextView
     android:text="@{dummy}"/>

用法:

mBinding.setDummy("DummyText")
4

1 回答 1

0

仅仅因为您将这两个选项视为完美的替代品,您就试图将成本(速度)最小化,即使从结果中基本上无法察觉差异。

事实是,即使两个选项的结果相同,当您决定(很可能)使用 ViewModel 和 LiveData 时,第二个选项可以为您提供更大的灵活性,因为它们为您提供了很多好处,只需对代码。

例如,您可以创建一个包含所有 MutableLiveData 的视图模型:

public class MyVM extends ViewModel {
    private MutableLiveData<String> title = new MutableLiveData<>();
    private MutableLiveData<String> text = new MutableLiveData<>();
}

将整个视图模型设置为 xml 中的变量并直接使用您的变量:

mBinding.setNiceViewModel(myVM);

<variable
     name="niceViewModel"
     type="MyVM" />

 ...
 <TextView
     android:text="@{niceViewModel.title}"/>

<TextView
     android:text="@{niceViewModel.text}"/>
于 2020-11-08T14:44:34.443 回答