Androidのボタンの背景色を設定するにはどうすればいいですか?

Androidで、ボタンの背景色を設定するには下記の方法があります。

  1. 背景の色を直接設定する方法を使用する
Button button = findViewById(R.id.button);
button.setBackgroundColor(Color.RED);
  1. XMLレイアウトファイルで背景色を設定する:

ResディレクトリのレイアウトフォルダにあるXMLレイアウトファイルで、ボタンの背景属性を追加する:

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/red" />

resディレクトリにあるvalues/colors.xmlで色を定義する

<resources>
<color name="red">#FF0000</color>
</resources>
  1. ボタンの背景色をセレクターで設定する:

res ディレクトリにある drawable フォルダに XML ファイルを作成して、button_selector.xml のようにします。これによりボタンの異なる状態における背景色が設定されます。

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/red" /> <!-- 按下状态的背景色 -->
<item android:state_focused="true" android:drawable="@color/blue" /> <!-- 获得焦点状态的背景色 -->
<item android:drawable="@color/green" /> <!-- 默认状态的背景色 -->
</selector>

そしてボタンにバックグラウンドとしてそのセレクタを指定するためにXMLレイアウトファイルで:

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button_selector" />

ご希望のボタンの背景色を上記の方法から設定できます。

bannerAds