LoginSignup
0

More than 5 years have passed since last update.

Androidのcheckboxの色を動的に変更させる

Last updated at Posted at 2018-03-23

意外にはまったの備忘録として記載しておきます。

Androidのcheckboxの色を動的に変更させる方法です。
xmlで変える方法は、あちこちで紹介されているのですが、
Javaのコードで動的に変える方法が中々見つかりませんでした。

今回、トグルボタンのON<->OFFでcheckboxの色を赤<->青に変更するコードを実装しました。

main
public class MainActivity extends AppCompatActivity {

    private CheckBox checkbox;
    private ColorStateList colorState; // 赤
    private ColorStateList colorState2;//青

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ToggleButton tButton = (ToggleButton) findViewById(R.id.toggleButton);
        tButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked) {
                    checkbox.setButtonTintList(colorState);//赤
                }else {
                    checkbox.setButtonTintList(colorState2);//青
                }
            }
        });

        checkbox = (CheckBox) findViewById(R.id.checkBox);
        colorState = new ColorStateList(
                new int[][] {
                        new int[]{ android.R.attr.state_checked},
                        new int[]{ -android.R.attr.state_checked},
                },
                new int[] {
                        Color.argb(0xff,0xff,0x00,0x00),
                        Color.argb(0xff,0xff,0x00,0x00),
                }
        );

        colorState2 = new ColorStateList(
                new int[][] {
                        new int[]{ android.R.attr.state_checked },
                        new int[]{ -android.R.attr.state_checked },
                },
                new int[] {
                        Color.argb(0xff,0x00,0x00,0xff),
                        Color.argb(0xff,0x00,0x00,0xff),
                }
        );
}

ColorStateListでcheckboxに指定したい色のカラーステートを作成して、
setButtonTintListでcheckboxにセットします。
ただ、setButtonTintListがAPI Level21からなので、Lollipop以降じゃないと使えないのご注意下さい。

実行結果は、こんな感じです。
赤.png
青.png

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
0