Androidボタンの色変更:基本と簡単カスタマイズ
Androidボタンの色を設定するには、以下の方法を使用します。
- XMLレイアウトファイルでボタンの背景色を設定します。
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:background="@color/colorPrimary" />
- Javaのコードでボタンの背景色を設定する方法:
Button button = findViewById(R.id.button);
button.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
- ボタンの異なる状態に色を設定するためにSelectorを使用する:
res/drawableフォルダにbutton_selector.xmlという名前のセレクタファイルを作成し、以下の内容を記述する。
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/colorAccent" />
<item android:drawable="@color/colorPrimary" />
</selector>
その後、ボタンの背景をこのセレクタに設定するために、レイアウトファイルやJavaコードで設定します。
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:background="@drawable/button_selector" />
上記の方法を使用して、Androidボタンの色を設定することができます。