Android:使用数据绑定的CardView前台

时间:2016-03-18 12:27:32

标签: android data-binding android-cardview

我正在尝试使用CardViews填充我的RecyclerView,CardViews使用Android数据绑定来设置TextViews中的文本等属性。在未完成喷射的物品上,我想添加灰色覆盖。但不幸的是,未应用前景android:foreground="@{viewModel.getState != State.FINISHED? @color/gray_transparent54 : null}">。另一方面,如果我强制使用前景色android:foreground="@grey_transparent54">,它就会起作用。

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <data class="ListItemBinder">
        <import type="myProject.State"/>
        <import type="android.view.View"/>
        <variable
            name="viewModel"
            type="myProject.ListItemViewModel"/>
    </data>

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        card_view:cardCornerRadius="4dp"
        android:foreground="@{viewModel.getState != State.FINISHED? @color/gray_transparent54 : null}">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@{viewModel.getName}"
                tools:text="Name"
                android:textColor="@color/color_text_primary"
                android:textSize="24sp"/>
    </android.support.v7.widget.CardView>
</layout>

提前致谢。

1 个答案:

答案 0 :(得分:0)

除非您已经实施了getGetState()getGetName()等getget,否则我认为您正在错误地访问viewModel字段。虽然您没有发布ListItemViewModel我怀疑您需要更接近这一点:

                                    

<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    card_view:cardCornerRadius="4dp"
    android:foreground="@{viewModel.state != State.FINISHED? @color/gray_transparent54 : null}">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{viewModel.name}"
            tools:text="Name"
            android:textColor="@color/color_text_primary"
            android:textSize="24sp"/>
</android.support.v7.widget.CardView>

数据绑定会自动在名为&#34; getName()&#34;的ListItemViewModel类中查找方法。当您访问@{viewModel.name}时,&#34; getState()&#34;当您访问@{viewModel.state}

注意:虽然UI逻辑通常没问题,但要小心将业务逻辑放在XML中,因为它会限制您的灵活性并使测试/调试更加困难。

还要知道在使用三元(?:)运算符时不能混合类型,因此在color int和drawable之间进行选择之类的东西将无效。但是,您可以使用自定义BindingAdapter方法轻松解决此问题,例如制作一个以ListItemViewModel为参数的绑定适配器,并将所有逻辑放在方法本身中设置的值类型。