LoginSignup
4
2

More than 3 years have passed since last update.

[Android]ボタン選択時に背景画像とテキスト色を同時に変更する方法

Last updated at Posted at 2019-07-31

つまり以下の様なことがやりたい

Image from Gyazo

ボタン選択時の背景画像を変更し、同時に文字の色を白にする。

<Button
    android:id="@+id/r_time_5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="5分以内"
    android:textColor="@drawable/refine_button_selector"
    android:background="@drawable/refine_button_selector"/>

上記のように、textColorとbackgroundにselectorを記載したファイル名を指定しておく


refine_button_selector.xmlにて、「state_selected」を設定し、選択中かそれ以外かを判定できるように。drawableに画像、colorに文字色をそれぞれ設定する

refine_button_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/select_btn_off" android:color="@color/black" android:state_selected="false" />
    <item android:drawable="@drawable/select_btn_on" android:color="@color/white" android:state_selected="true" />
</selector>


あとはonClickで処理してやるだけ

rTime5 = findViewById(R.id.r_time_5);
rTime5.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        v.setSelected(!v.isSelected());
        if(v.isSelected()){
            //・・・選択時に行いたい処理・・・
        }
    }
});

たまに実装しようとした際に迷うので備忘としてあげておきます

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2