棒棒糖(Lollipop)的背景色(backgroundTint)对按钮(Button)没有影响。

87

我在我的Activity中有一个按钮,我希望它具有我的主题的强调颜色。与其像在Lollipop之前必须做的那样制作自己的可拉伸图形,我希望使用新的backgroundTint属性。

<Button
    android:id="@+id/btnAddCode"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:backgroundTint="@color/accent"
    android:text="@string/addressInfo_edit_addCode" />

很不幸,它没有效果,按钮仍然是灰色的。

我尝试了不同的backgroundTintMode值,但没有改变任何东西。

我还尝试在我的Activity中编程实现,但也没有改变任何东西。

addCodeView.findViewById(R.id.btnAddCode).setBackgroundTintList(
     getResources().getColorStateList(R.color.accent));

为什么我的着色被忽略了?

编辑: 只是为了澄清,我确实在一个棒棒糖设备上测试。 其它小部件(例如EditText)会正确且自动地进行着色。


3
这是一个已经被修复,将在未来版本中更新的错误,但接受的解决方案可在API 21+上运行。 - alanv
请查看此更新的答案 - Amit Vaghela
16个回答

0

我不确定这是否被推荐,但你可以尝试一下:

Drawable newDrawable = mBtnAction.getBackground();  // obtain Bg drawable from the button as a new drawable
DrawableCompat.setTint(newDrawable, mActivity.getHomeTobBarBGColor());  //set it's tint
mBtnAction.setBackground(newDrawable);  //apply back to button

一般来说它能正常工作。尝试了ViewCompat,但似乎无法正常工作。

0

如果你正在开发一个目标sdk高于API 21的应用,并且你的minSdkVersion是21(棒棒糖)而不是

android:backgroundTint="@color/accent"

你可以简单地说...

android:background="@color/accent"

0

您可以使用backgroundTint <android.support.design.button.MaterialButton,版本为"com.android.support:design:28.0.0-rc01"


0

由于属性backgroundTint仅在API级别21及以上版本中使用


我意识到了这一点,而且我确实正在一台棒棒糖设备上进行测试。我会更新问题以澄清这一点。 - BoD

0

请注意,RecyclerView最新的库也可能会导致此错误。

此命令

  sendBtnView.setBackgroundTintList(colorState)

过去一直运行得很好,但现在对我来说停止工作了。经过研究发现原因是添加到Gradle依赖项中的库:

  compile 'com.android.support:recyclerview-v7:+'

我尝试将其更改为23.02.1,因为在Amit Vaghela的帖子中建议如此。我已经更改为

  compile  'com.android.support:recyclerview-v7:23.02.1'

但是Gradle错误提示RecyclerView库没有这个版本(23.02.1)(Gradle在Jcenter raw.github或repo中找不到它)。

然后,因为我知道setBackgroundTintList命令在过去的22.02.0版本中与我在Gradle依赖中拥有的其他库一样都可以正常使用, 所以我将其更改为:

compile   'com.android.support:recyclerview-v7:22.02.0'

现在它又可以工作了。


0
如果您正在使用androidx,则在Android 5.1上添加前缀和非前缀版本可以解决问题:
<style name="Button_Primary">
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:backgroundTint">@color/button_primary_selector</item>
    <item name="backgroundTint">@color/button_primary_selector</item><!--needed for android 5-->
</style>

button_primary选择器位于color文件夹中,其内容如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:local="http://schemas.android.com/apk/res-auto">
    <item android:state_enabled="true" android:color="@android:color/holo_blue_dark" />
    <item android:state_enabled="false" android:color="@android:color/darker_gray" />
</selector>

并将其应用于AppCompatActivity上的普通按钮

<Button style="@style/Button_Primary"/>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接