意外にはまったの備忘録として記載しておきます。
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以降じゃないと使えないのご注意下さい。