Я хочу использовать троичный оператор, чтобы изменить цвет пользовательского представления в терминах логического значения. Вот мой пользовательский вид
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), android.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}"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Он работает, как и ожидалось, для приложения: текст, но когда я хочу сделать это для iconColor, у меня появляется эта ошибка:
Cannot find a setter for <com.my.package.ui.customview.AddButton app:iconColor> that accepts parameter type 'int'
На данный момент, чтобы решить проблему, я должен измените цвет в коде, слушая, когда меняется выбранный логический тип, и затем вызывайте setIconTint моего представления AddButton.
Есть ли способ изменить цвет непосредственно в файле макета с помощью троичного оператора?