You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Android XML布局:如何将自定义属性值设为组件另一属性值?

当然可以实现!不过你当前的写法有问题

你尝试的app:unfocusColor="@{app:cardBackgroundColor}"语法不对,Data Binding里引用控件自身的属性需要通过控件实例来访问,而不是直接用命名空间+属性名的方式。

下面给你两种可行的正确写法:

方法一:给控件设置ID后引用

给你的CardView添加一个ID,然后通过ID来访问它的cardBackgroundColor属性:

<android.support.v7.widget.CardView
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="@android:color/holo_blue_bright"
    app:unfocusColor="@{cardView.cardBackgroundColor}">
    <!-- 你的子布局内容 -->
</android.support.v7.widget.CardView>

方法二:使用this关键字直接引用自身

如果不想额外加ID,也可以用this来指代当前控件实例:

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="@android:color/holo_blue_bright"
    app:unfocusColor="@{this.cardBackgroundColor}">
    <!-- 你的子布局内容 -->
</android.support.v7.widget.CardView>

额外注意事项

  • 确保开启Data Binding:这种表达式依赖Data Binding框架,你需要在app模块的build.gradle中开启它:
    android {
        ...
        buildFeatures {
            dataBinding true
        }
    }
    
  • 类型匹配:自定义属性unfocusColor的类型必须和cardBackgroundColor一致(比如都是int或者ColorStateList),否则会出现类型不匹配的编译错误。

内容的提问来源于stack exchange,提问作者Nick Wills

火山引擎 最新活动