[英]How to set visibility for include layout in databinding?
我已經在我的項目中實現了數據綁定。 我有一個特定的屏幕,在 include 標簽中有兩個嵌套的布局。 我無法以編程方式使用數據綁定更改包含布局的可見性。
但是,我已經通過布爾值實現了它,但我的問題是如何以編程方式設置包含標記的可見性。
我的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"/>
在活動中:當我嘗試設置它時 - 它變成紅色,這意味着它不會將其視為視圖。
dataBinding.regPhone.setVisibility(View.GONE);
dataBinding.regEmail.setVisibility(View.VISIBLE);
將 get root 添加到您的視圖中
dataBinding.regPhone.getRoot().setVisibility(View.GONE);
dataBinding.regEmail.getRoot().setVisibility(View.VISIBLE);
更好的辦法。
在頂部布局上,聲明布爾值或可觀察字段,其值可切換所包含布局的可見性。 然后記得給包含的布局一個id
否則它不會工作
<?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>
使用參考視圖 ID 為我創建組,因為我使用<merge>
標記包含布局。
<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}"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.