简体   繁体   中英

Android databinding importing view into XML

I have seen 2 approaches for setting Visibility in XML using Databinding

  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.

The first one is the better.

  1. Checks if showLoader is true then sets the views visibility to visible else gone.
  2. The second one is passing a boolean showLoader as the view's visibility which should end up throwing an error.

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.

For example:

Create BindingAdapters.kt file and put this code in it

@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}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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