Buttonにスタイルを設定する
そりゃそうだよねって感じではあるんだけど、あれこれどうするっけ…
ってよく調べなおすので自分で書いて覚えよう選手権を開催します。
よくあるシーン
ボタンに背景色つけるぞ!ボタンの文字色も変えるぞ!
ちゃんとenabled
を設定して制御するぞ!
困った!enabled=false
なのに背景色も文字色も変わらん!OMG!
解決策
ColorStateList
でボタンの状態に応じた色を背景色・文字色に設定しよう!
せっかくだし、スタイルで定義しちゃおう!
ColorStateList
たとえば、 enabled=false
のときの色は別で!なときは
res/color/background_primary.xml
のようなファイルを作って
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@android:color/darker_gray" android:state_enabled="false"/> <item android:color="@color/colorPrimary"/> </selector>
としてあげるだけ。便利!
スタイルに設定してあげる
これを文字色も同じように作ってあげて、
<!-- Buttonのスタイル --> <style name="Material.RadiusButton" parent="Widget.MaterialComponents.Button.UnelevatedButton"> <item name="backgroundTint">@color/background_primary</item> <item name="rippleColor">@color/colorAccent</item> <item name="android:layout_height">@dimen/button_height_base</item> <item name="cornerRadius">@dimen/button_radius_base</item> <item name="android:textColor">@color/button_text</item> </style>
ボタンにスタイルを適用する
<android.support.design.button.MaterialButton android:id="@+id/button" style="@style/Material.RadiusButton" android:layout_width="match_parent" android:enabled="@{!viewModel.executing}" android:onClick="@{() -> viewModel.onClick()}" android:text="@string/button_text"/>
とすれば、管理が楽ですね!めっちゃ説明を端折りました!
まとめ
書いたらきっと思い出せる!便利!