Android Data Binding: visibility on include tag

前端 未结 9 709
旧时难觅i
旧时难觅i 2020-12-24 10:38

As per http://developer.android.com/tools/data-binding/guide.html#imports, we can have such simple expressions in visibility:



        
相关标签:
9条回答
  • 2020-12-24 11:29

    This is a bit late, but I have run across this recently.

    I believe this is actually a bug in the Data Binding compiler as it is possible to set android:visibility attribute on <include> tag directly (ie. without Databinding).

    0 讨论(0)
  • 2020-12-24 11:34

    A better way.

    On the top layout, declare the boolean or an observable field whose value toggle the visibility of the included layout. Then remember to give the included layout an id else it wont work

    <?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools">
        <data>
            <import type="android.view.View"/>
            <variable
                name="show"
                type="Boolean" />
        </data>
        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:background="@color/colorPrimary">
    
    
            <include layout="@layout/progress"
                android:id="@+id/progress"
                android:visibility="@{show?View.VISIBLE:View.GONE}"/>
    
        </androidx.constraintlayout.widget.ConstraintLayout>
    </layout>
    
    0 讨论(0)
  • 2020-12-24 11:37

    This is the direct approach, without having to pass the variable inside the included layout

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <include
            layout="@layout/layout_errors"
            android:visibility="@{isVisible ? 0:1 }"
           />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    The above code was all I needed

    The interesting thing is if I remove the above ternary operator and simplify it like this,

    <include
        layout="@layout/layout_errors"
        android:visibility="@{isVisible}"
       />
    

    with addition of an BindingAdapter class with following method,

    @BindingAdapter("android:visibility")
        public static void setVisibility(View view, boolean isVisible) {
            view.setVisibility(isVisible ? View.VISIBLE : View.GONE);
        } 
    

    Boom! the OP error invades my entire BuildOutput trace, interesting world of Android

    0 讨论(0)
提交回复
热议问题