Databinding variable inheritance with included layout

后端 未结 3 2416
一个人的身影
一个人的身影 2021-02-20 00:40

I am learning data binding and mvvm. I have an issue where I would like a BaseViewModel.kt to include some UI related variables such as an isLoading fl

相关标签:
3条回答
  • 2021-02-20 01:30

    You can use binding with include like

    loading_view.xml

    <?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        >
    
        <data>
    
            <import type="android.view.View"/>
    
            <variable
                name="visibility"
                type="boolean"
                />
    
            <variable
                name="text"
                type="String"
                />
        </data>
    
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#ff0"
            android:gravity="center_horizontal"
            android:orientation="vertical"
            android:visibility="@{visibility?View.VISIBLE:View.GONE}"
            >
            <ProgressBar
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="@{text}"
                tools:text="AA"
                />
        </LinearLayout>
    </layout>
    

    Using

    <include
            layout="@layout/loading_view"
            app:visibility="@{viewModel.loadingCondition}"
            app:text='@{"AA"}'
            />
    

    you can also pass the hard value like

    app:visibility="@{false}"
    app:text="@{@string/loading_text}"
    
    0 讨论(0)
  • 2021-02-20 01:32

    for those who still don't have solution, just check your code and check whether the name of "bind" attribute is same as the one used in the included layout

    <include
           ...
            bind:viewModel="@{viewModel}"/>
    

    and

    <data>
        ...
        <variable
            name="viewModel"
            type="core.sdk.ui.base.BaseViewModel" />
    
    </data>
    
    0 讨论(0)
  • 2021-02-20 01:35

    I think you should cast it in the binding:

    <include
        android:id="@+id/progress_include"
        layout="@layout/progress_bar"
        android:visibility="@{viewModel.isLoading ? View.VISIBLE : View.GONE}"
        bind:viewModel="@{(core.sdk.ui.base.BaseViewModel)viewModel}"/>
    
    0 讨论(0)
提交回复
热议问题