カスタムビューのカスタムカラー属性のAndroid三項演算子

BenCLT:

私は、ブールの面でカスタムビューの色を変更するには三項演算子を使用します。ここに私のカスタムビューがあります

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
}
}

値/ attr.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'

今の問題を解決するために、私は、ブール値の変更を選択したときのリスニングで後ろにコードの色を変更して、私のAddButtonビューのsetIconTintを呼び出す必要があります。

三項演算子を使用してレイアウトファイルで直接色を変更する方法はありますか?

モハマド・Omidvar:

あなたのカスタムビュー用のアダプタをバインドするカスタムデータを探しています。まず、チェックアウトこれを完全な文書について。

:だから、簡単に言えば、あなたは名前のメソッドを定義する必要がsetIconColor受け付けiconIdと提供されるリソースIDでアイコンの色を設定します。

あなたの現在の方法は、名前の使用したい場合しかしsetIconTint、あなただけで、あなたのクラスに注釈を付ける必要があります。

@BindingMethods(value = [
BindingMethod(
    type = AddButton::class,
    attribute = "iconColor",
    method = "setIconTint")])

すべての後、私は再びあなたが公式文書にアダプタを結合する他の変異体を確認してください示唆しています。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=341445&siteId=1