简体   繁体   中英

How to set visibility for include layout in databinding?

I have implemented data binding in my project. I have a particular screen with two nested layouts in include tags. I couldn't change the visibility for include layouts using data binding programmatically.

However, I have achieved it through a boolean, but my question is how to set visibility for that include tag programmatically.

My xml:

<include
  android:id="@+id/reg_email"
  layout="@layout/custom_email"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>


<include
  android:id="@+id/reg_phone"
  layout="@layout/custom_phone"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>

And in Activity: when I try to set this - it becomes red meaning it doesn't take it as a view.

  dataBinding.regPhone.setVisibility(View.GONE);
  dataBinding.regEmail.setVisibility(View.VISIBLE);

add get root to your view

dataBinding.regPhone.getRoot().setVisibility(View.GONE);
dataBinding.regEmail.getRoot().setVisibility(View.VISIBLE);

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>

Create the group with reference view id's work for me because I am including the layout using <merge> tag.

 <androidx.constraintlayout.widget.Group
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:constraint_referenced_ids="emptyStateView,emptyStateDescription"
        android:visibility="@{viewModel.searchResultState.result.size() == 0 ? 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