简体   繁体   中英

How to add ripple effect with gradient to button?

I created a button and I want to add ripple effect and gradient to that button!

Here is my Button code:

<Button
    android:id="@+id/percentageButton"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:background="@drawable/gradient"
    android:gravity="center"
    android:text="%"
    android:textColor="@android:color/white"
    android:textSize="30dp">
</Button>

Here is my gradient.xml file code

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <corners
        android:radius="0dp"/>
    <gradient
        android:gradientRadius="100"
        android:centerX="49%"
        android:centerY="50%"
        android:centerColor="#434343"
        android:startColor="#0F0F0F"
        android:endColor="#141414"
        android:type="radial"/>
  </shape>

I have tried all the possibilities but not getting how to achieve this.

To get the ripple effect when you press a button, simply change your button xml to include:

android:foreground="?attr/selectableItemBackground"

and to have a basic gradient on your button you can have:

 <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <gradient
            android:angle="-90"
            android:startColor="COLORHERE"
            android:endColor="COLORHERE"
            android:type="linear" />
    </shape>

android:foreground didn't work for me in Lollipop and here are my xml drawable for the button. Add button_background.xml to your drawable.

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/colorPrimaryDark">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="@color/colorPrimaryDark" />
            <corners android:radius="@dimen/button_radius_large" />
        </shape>
    </item>

    <item android:id="@android:id/background">
        <shape android:shape="rectangle">
            <gradient
                android:angle="90"
                android:endColor="@color/colorPrimaryLight"
                android:startColor="@color/colorPrimary"
                android:type="linear" />
            <corners android:radius="@dimen/button_radius_large" />
        </shape>
    </item>
</ripple>

Add this to the background of your button.

<Button
    ...
    android:background="@drawable/button_background" />

Note : Attribute android:foreground has no effect on API levels lower than 23

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM