AndroidStudio : selector で background に色変更をつけたい

公式リンク

https://developer.android.com/guide/topics/resources/color-list-resource?hl=ja

上のリンクは state_pressed とかの変数まとめ state_pressed は押されているとき。

xml で設定する方法とjava,kotlinで設定する方法がある(当然)

view_pressed_selector_drawable.xml (色変える用の xml)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/off_white" android:state_pressed="true"/>
    <item android:drawable="@color/white"/>
</selector>

drawable を設定しないとエラーがでてくる。background だから color 設定すればええやんと思ってたらそんなことなかった

xml で呼び出す場合

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:descendantFocusability="blocksDescendants"
    android:background="@drawable/view_pressed_selector_drawable"
    xmlns:app="http://schemas.android.com/apk/res-auto">
//中に適当に書く
</androidx.constraintlayout.widget.ConstraintLayout>

下のコードで設定

android:background="@drawable/view_pressed_selector_drawable"

Kolin で呼び出す場合(onCreate 等でいい感じに呼び出す)

itemView.setBackgroundResource(R.drawable.view_pressed_selector_drawable)

itemView は色変えたい View にする。

ひとこと

drawable じゃなくて color 設定して押し通そうとしたせいでずっとエラーだったのほんま.........

エラー内容

<item> tag requires a 'drawable' attribute or child tag defining a drawable

 

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA