androidbuttonthemesborderless

How to make a shadowless coloured button in Android


I've been trying various ways to do this through styles but cannot get what I want. It seems I can have a coloured button with a shadow or a button with no shadow for which I can only change the text and pressed colours.

Here's what I have in my styles.xml:

<style name="PrimaryFlatButton"  parent="Theme.AppCompat.Light">
    <item name="colorControlHighlight">@color/colorPrimary</item>
    <item name="colorButtonNormal">@color/colorPrimaryLight</item>
</style>

and here is what I have in my layout:

<Button
    android:id="@+id/btn_search"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/pc_large_padding"
    android:theme="@style/PrimaryFlatButton"
    style="@style/Widget.AppCompat.Button"
    android:text="Search"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintRight_toRightOf="parent"/>

Which gives me a coloured button which darkens when pressed but has a shadow.

If I change the button to have a style of:

style="@style/Widget.AppCompat.Button.Borderless"

Then I successfully lose the shadow but get no background colour unless the button is pressed. I presume Android's idea of "borderless" means having nothing to indicate a border at all - just plain text - rather than making a flat button.

All I want is the standard themed button, with a background colour, which changes colour when pressed, and has no shadow.


Solution

  • You should be able to get a colored button complete with the ripple effect by creating a selector drawable and specifying it as the button's background. Something like this:

    some_layout.xml

    <Button
       style="@style/Theme.Flat.Button"
       <!-- Any other properties you want to set -->
       />
    

    style.xml

    <style name="Theme.Flat.Button" parent="@style/Widget.AppCompat.Button.Borderless">
        <item name="android:background">@drawable/ripple_selector</item>
        <!-- Any other items you want to add -->
    </style>
    

    ripple_selector.xml

    <ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="@color/colorPrimary">
        <item>
            <selector>
                <item android:state_enabled="false">
                    <color android:color="@color/colorPrimaryLight" />
                </item>
                <item android:state_enabled="true" android:state_pressed="false">
                    <color android:color="@color/colorPrimaryLight" />
                </item>
                <item android:state_enabled="true" android:state_pressed="true">
                    <color android:color="@color/colorPrimary" />
                </item>
            </selector>
        </item>
    </ripple>