简体   繁体   English

Android 数据绑定导入视图到 XML

[英]Android databinding importing view into XML

I have seen 2 approaches for setting Visibility in XML using Databinding我已经看到了两种使用数据绑定在 XML 中设置可见性的方法

  1. <variable name="vm" type="com.example.myapp.viewmodel.MyViewmodel" /> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <ProgressBar style="@style/ProgressBarMediumWhite" android:visibility="@{vm.showLoader? View.VISIBLE: View.GONE}" />
  2.  <variable name="vm" type="com.example.myapp.viewmodel.MyViewmodel" /> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <ProgressBar style="@style/ProgressBarMediumWhite" android:visibility="@{vm.showLoader}" />

I want to know which one is the better approach or both seems to be good.我想知道哪个是更好的方法,或者两者似乎都很好。 How bad it is to Import android view in to the XML file.将 android 视图导入 XML 文件是多么糟糕。

The first one is the better.第一个更好。

  1. Checks if showLoader is true then sets the views visibility to visible else gone.检查showLoader是否为真,然后将视图visibility设置为可见,否则消失。
  2. The second one is passing a boolean showLoader as the view's visibility which should end up throwing an error.第二个是通过 boolean showLoader作为视图的可见性,这最终会引发错误。

Both approaches are the same, there is no difference.两种方法都是一样的,没有区别。

However, there is one more way to create binding adapter and use it in xml layout files for changing visibility.但是,还有另一种方法可以创建绑定适配器并在 xml 布局文件中使用它来更改可见性。

For example:例如:

Create BindingAdapters.kt file and put this code in it创建BindingAdapters.kt文件并将此代码放入其中

@BindingAdapter("goneUnless")
fun goneUnless(view: View, visible: Boolean) {
    view.visibility = if (visible) VISIBLE else GONE
}

Now you can use this binding adapter like this现在你可以像这样使用这个绑定适配器

<ProgressBar
    style="@style/ProgressBarMediumWhite"
    app:goneUnless="@{vm.showLoader}" />

In most cases, both approaches work just fine.在大多数情况下,这两种方法都可以正常工作。

However, when you have to make a choice like this, always choose the option that does not involve passing a view as a parameter.但是,当您必须做出这样的选择时,请始终选择不涉及将视图作为参数传递的选项。 Unexpected events from the source (where the parameter comes from) might cause your app to misbehave or cause the view to render wrongly.来自源(参数的来源)的意外事件可能会导致您的应用程序行为异常或导致视图呈现错误。

Therefore, the first approach seems to be more reliable .因此,第一种方法似乎更可靠

android:visibility="@{vm.showLoader ? View.VISIBLE : View.GONE}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM