Android ripple background color

风格不统一 提交于 2019-11-28 18:11:29

You can control the colour of the RippleDrawable by doing the following:

RippleDrawable rippleDrawable = (RippleDrawable)view.getBackground(); // assumes bg is a RippleDrawable

int[][] states = new int[][] { new int[] { android.R.attr.state_enabled} };
int[] colors = new int[] { Color.BLUE }; // sets the ripple color to blue

ColorStateList colorStateList = new ColorStateList(states, colors);
rippleDrawable.setColor(colorStateList);

Or, via XML:

<?xml version="1.0" encoding="utf-8"?>
<ripple
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="#FFFF0000"> <!-- The ripple will be red -->

    <!-- the normal bg color will be light grey -->
    <item>
        <color android:color="#FFDDDDDD" />
    </item>

    <!-- make sure the ripple doesn't exceed the bounds -->
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="?android:colorAccent" />
        </shape>
    </item>
</ripple>

EDIT

After seeing @i.shadrin's answer below, I must admit it's a much simpler approach (using styles). If this is an option for you, I would recommend it.

It's a lot easier to do with styles:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
   ...
   <item name="colorControlHighlight">@color/ripple_material_dark</item>
   ...
</style>

add these two line of code inside of your view to give ripple effect .

android:clickable="true"
android:background="?attr/selectableItemBackground"

If you are using the custom button color then use below code for ripple effect. Save the file in drawable with name my_ripple.xml and set in background of button.

 <?xml version="1.0" encoding="utf-8"?>
 <ripple xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:too`enter code here`ls="http://schemas.android.com/tools"
    android:color="@color/ripple_color"
    tools:targetApi="lollipop">
    <item android:id="@android:id/mask">
     <shape android:shape="rectangle">
        <solid android:color="@color/ripple_color"
            />
    </shape>
  </item>
  <item
    android:id="@android:id/background"
    android:drawable="@color/button_color" />
 </ripple>

An example ripple to use with a selector on api lvl 21 and above

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="?attr/colorControlHighlight">

    <!-- ripple mask -->
    <item android:id="@+id/mask">
        <color android:color="@android:color/white"/>
    </item>

    <!-- background shape or color -->
    <item android:drawable="@drawable/rectangle_rounded_steel_blue"/>

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