Search code examples
androidandroid-layoutandroid-5.0-lollipop

Styling a AppCompatButton in v21 to have no shadow and corner radius of zero


I have a AppCompatButton defined in a XML layout, and I have set a theme for it like this:

android:theme="@style/CustomAccentOverlay"

And I have set:

android:stateListAnimator="@null"

to remove the shadow. I have two problems with this.

The height of the button is deducted the height of the shadow, even though the shadow is not shown. Should I remove the shadow in some other way, or how do I fix this?

The button has rounded corners, and I want the corners to be sharp. I can not set a background on the button, because I want to keep the standard ripple effect and that goes away if I set a background (at least I don't know how to keep it if I set a background). I have tried setting

<item name="android:bottomLeftRadius">0dp</item>

and all the other corners to the CustomAccentOverlay theme and also its corresponding style, but it does not work. How can I set the corner radius to zero on my button?

Thank you
Søren


Solution

  • Use the following code for the Button.

    <android.support.v7.widget.AppCompatButton
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:text="Button"
    android:stateListAnimator="@null"
    android:elevation="0dp"
    android:background="@android:color/darker_gray"
    android:foreground="?attr/selectableItemBackground"
    />
    

    I will explain the attributes.

    1. android:elevation="0dp" and android:stateListAnimator="@null". No shadow for the button.

    2. android:background . Set the desired color as background. It removes the rounded corners.

    3. android:foreground="?attr/selectableItemBackground" . It gives the ripple effect when the button is pressed.

    Update 1:

    It seems like android:foreground attribute for View works from API 23. For below APIs, create a drawable with ripple in drawable-v21 folder and set it as background to the button,

    <ripple
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        tools:ignore="NewApi"
        android:color="@color/ripple_color">
    
        <item android:drawable="@color/normal_state_button_background_color"/>
    
    </ripple>
    

    For pre Lollipop versions, create a drawable with selector in drawable folder with the same name.

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/pressed_color"
              android:state_pressed="true" />
        <item android:drawable="@drawable/focused_color"
              android:state_focused="true" />
        <item android:drawable="@drawable/normal_color" />
    </selector>