如何在Android 5.0 Lollipop中以代码方式(而非xml)以编程方式使用RippleDrawable?
我的涟漪代码如下:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?android:colorControlHighlight">
<item android:id="@+id/rip">
<shape android:shape="oval">
<solid android:color="?android:colorAccent"/>
</shape>
</item>
</ripple>
现在,我想让用户可以选择自己的颜色,因此我需要以编程方式创建波纹.
我发现了此,我认为这是正确的方法它,但我不知道该如何处理.
Now I want to give the user the possibility to choose own colors, so I need to create the ripple programmatically.
I found this and I think this is the right way to do it, but I don't know how to handle with this.
波纹将在这里使用:
<ImageButton
android:id="@+id/add_button"
android:layout_width="@dimen/diameter"
android:layout_height="@dimen/diameter"
android:layout_gravity="end|bottom"
android:layout_marginBottom="@dimen/add_button_margin"
android:layout_marginEnd="@dimen/add_button_margin"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:src="@drawable/ic_action_add_person"
android:tint="@android:color/white"
android:background="@drawable/oval_ripple"
android:elevation="@dimen/elevation_low"
android:stateListAnimator="@anim/button_elevation"
android:contentDescription="Neuer Spieler" />
我需要像这样将背景设置为RippleDrawable
:
I need to set the background to a RippleDrawable
like this:
addButton.setBackground(ripple);
这就是我实现此目标的方式.
This is how I was able to achieve this.
请注意,这仅是Api 21+,因此,如果您支持较低版本,则必须回退到普通的Drawable.
public static RippleDrawable getPressedColorRippleDrawable(int normalColor, int pressedColor)
{
return new RippleDrawable(getPressedColorSelector(normalColor, pressedColor), getColorDrawableFromColor(normalColor), null);
}
public static ColorStateList getPressedColorSelector(int normalColor, int pressedColor)
{
return new ColorStateList(
new int[][]
{
new int[]{android.R.attr.state_pressed},
new int[]{android.R.attr.state_focused},
new int[]{android.R.attr.state_activated},
new int[]{}
},
new int[]
{
pressedColor,
pressedColor,
pressedColor,
normalColor
}
);
}
public static ColorDrawable getColorDrawableFromColor(int color)
{
return new ColorDrawable(color);
}
修改: 我对此进行了更多修改,发现ColorStateList不需要像上述解决方案一样复杂.我已将其简化为以下代码段. (以上代码块中的所有其他内容都是相同的.我只更改了ColorStateList的创建.)如果此方法不适用于某人,则将上面的块保留为原始代码.
I tinkered with this some more and discovered that the ColorStateList doesn't need to be nearly as complex as the above solution. I have simplified it to the below snippet. (Everything else in the above code block is the same. I only changed the ColorStateList creation.) I will leave the above block as the original, in case this method doesn't work for someone.
new ColorStateList(
new int[][]
{
new int[]{}
},
new int[]
{
pressedColor
}
);