首页 > 解决方案 > Android如何在Button上设置背景颜色

问题描述

我正在尝试更改按钮的背景颜色。我在模拟器上使用 SDK 21 的 Kotlin。

在布局 XML 文件中声明了一个 View 和一个 Button

<View
    android:id="@+id/myview"
    android:layout_width="64dp"
    android:layout_height="32dp"
    />
<Button
    android:id="@+id/showButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="12dp"
    android:text="test"
    />

设置颜色的 API 似乎不起作用:

    showButton.setBackgroundColor(0xff60a0e0.toInt()) <-- doesnt work

有效的是:

    myview.setBackgroundColor(0xff60a0e0.toInt()) <-- works, exact background color
    showButton.setTextColor(0xff000050.toInt()) <-- works, exact text color

进一步尝试后,似乎我只能设置按钮的 alpha 通道,而不是颜色:

    setBackgroundColor( 0xff000000.toInt())  <-- works, opaque
    setBackgroundColor( 0x00000000.toInt())  <-- works, transparent

同样的事情:

        showButton.setBackgroundColor(Color.GREEN) <-- doesnt work, button is opaque but not green
        showButton.setBackgroundColor(Color.TRANSPARENT) <-- works, button is transparent

任何的想法?我是否遗漏了其他答案或文档中的某些内容?

这是完整的布局,它用于膨胀片段,如果这很重要:



    <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
           <View
               android:id="@+id/myview"
               android:layout_width="64dp"
               android:layout_height="32dp"
              />
           <Button
               android:id="@+id/showButton"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:text="12dp"
               android:text="test"
               />
        </LinearLayout>
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/dictionaryEntryRecyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="vertical"
            app:layoutManager="LinearLayoutManager"
            />
       </LinearLayout>

标签: androidkotlinandroid-buttonmaterial-componentsmaterial-components-android

解决方案


mButton.setBackgroundColor(ContextCompat.getColor(mContext, R.color.xxx));


推荐阅读