Androidでボタンの背景色を変更する方法は何ですか?

AndroidのButtonの背景色を変更したい場合は、次の方法を使用することができます。

  1. 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ファイルで定義することができます。

  1. Javaコードでボタンの背景色を設定する方法:
Button myButton = findViewById(R.id.myButton);
myButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
  1. リソース/ドローアブル
  2. ボタンの選択を行うための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" />
コメントを残す 0

Your email address will not be published. Required fields are marked *


广告
広告は10秒後に閉じます。
bannerAds