自定义视图的自定义颜色属性上的java Android三值运算符
我想用三元操作符来改变一个自定义视图的颜色。 这是我的自定义视图
class AddButton(context: Context, attrs: AttributeSet): RelativeLayout(context, attrs) {
private var imageView: AppCompatImageView
private var textView: TextView
init {
inflate(context, R.layout.add_button, this)
imageView = findViewById(R.id.add_button_icon)
textView = findViewById(R.id.add_button_text)
val attributes = context.obtainStyledAttributes(attrs, R.styleable.AddButton)
val iconTint = attributes.getResourceId(R.styleable.AddButton_iconColor, 0)
imageView.setImageDrawable(attributes.getDrawable(R.styleable.AddButton_icon))
textView.text = attributes.getString(R.styleable.AddButton_text)
setIconTint(iconTint)
attributes.recycle()
}
fun setIconTint(colorId: Int) {
imageView.setColorFilter(ContextCompat.getColor(context, colorId), 安卓.graphics.PorterDuff.Mode.SRC_IN);
}
fun setText(text: String) {
textView.text = text
}
}
价值观/属性。xml:
<declare-styleable name="AddButton">
<attr name="icon" format="reference"/>
<attr name="iconColor" format="color"/>
<attr name="text" format="string"/>
</declare-styleable>
在布局中:
<com.my.package.ui.customview.AddButton
app:icon="@drawable/ic_add"
app:iconColor="@{selected ? @color/colorRed : @color/colorBlack}"
app:text="@{selected ? @string/selected : @string/not_selected}"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"/>
它在app:text上的效果与预期一样,但当我想在iconColor上运行时,我出现了以下错误:
Cannot find a setter for <com.my.package.ui.customview.AddButton app:iconColor> that accepts parameter type 'int'
现在,为了解决这个问题,我必须通过监听所选布尔值的变化来改变代码中的颜色,然后调用AddButton视图的setIconTint
有没有办法使用三元运算符直接更改布局文件中的颜色
共 (0) 个答案