Androidでボタンの背景色を変更する方法は何ですか?
AndroidのButtonの背景色を変更したい場合は、次の方法を使用することができます。
- XMLのレイアウトファイルでButtonの背景色を設定する。
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:background="@color/colorPrimary" />
この例では、@color/colorPrimaryは色のリソースであり、res/values/colors.xmlファイルで定義することができます。
- Javaコードでボタンの背景色を設定する方法:
Button myButton = findViewById(R.id.myButton);
myButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
- リソース/ドローアブル
- ボタンの選択を行うためのXMLファイル
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/colorPrimaryDark" />
<item android:drawable="@color/colorPrimary" />
</selector>
ボタンのXMLレイアウトファイルで背景を設定します。
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:background="@drawable/button_selector" />