Can't set background color of button using Material Components library

折月煮酒 提交于 2020-05-15 08:03:07

问题


My code:

<Button
     android:id="@+id/button_one"
     style="@style/ButtonStyle"
     android:text="@string/button_one" />
<style name="ButtonStyle">
     <item name="android:textSize">32sp</item>
     <item name="android:textColor">@drawable/background_button_text_color</item>
     <item name="android:background">@drawable/background_button</item
</style>

background_button.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:color/white" android:state_pressed="true" />
    <item android:drawable="@android:color/transparent" android:state_pressed="false" />
</selector>

background_button_text_color.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@android:color/black" android:state_pressed="true" />
    <item android:color="@android:color/white" android:state_pressed="false" />
</selector>

I am getting a black background instead of white when the button is pressed. Not sure what I'm doing wrong. Any help?
I am on 1.2.0-alpha06 and using Theme.MaterialComponents.DayNight.NoActionBar.


回答1:


Your style:

<style name="ButtonStyle" parent="Widget.MaterialComponents.Button.TextButton">
    <item name="android:textSize">32sp</item>
    <item name="android:textColor">@color/text_color</item>
    <item name="android:backgroundTint">@color/background_button</item>
    <item name="rippleColor">@android:color/transparent</item>
    <item name="cornerRadius">0dp</item>
</style>

Your selectors should be in color folder

background_button:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:color="@android:color/white" android:state_pressed="true" />
   <item android:color="@android:color/transparent" android:state_pressed="false"/>
</selector>

text_color:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:color="@android:color/black" android:state_pressed="true" />
   <item android:color="@android:color/white" android:state_pressed="false" />
</selector>

And add to your button:

android:layout_width="wrap_content"
android:layout_height="wrap_content"

Colors are mine




回答2:


Ran into the same issue, setting app:backgroundTint="@null" was what worked for me. See full solution here: https://github.com/material-components/material-components-android/issues/889#issuecomment-621194246



来源:https://stackoverflow.com/questions/61365797/cant-set-background-color-of-button-using-material-components-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!