如何在 Java 中为多个按钮动态应用一个波纹可绘制对象?

How to apply the one ripple drawable for multiple buttons dynamically in Java?

我想在多个按钮上正确应用相同的波纹可绘制对象。但这并没有发生,因为连锁反应只应用在最后一个按钮上。我还在波纹可绘制对象中使用了渐变可绘制对象。这在每个按钮上都可以正常工作。只是涟漪效应没有应用到除最后一个按钮之外的任何按钮上。它也不适用于 api 级别 8。我知道此方法不适用于 api 之前的 api 级别 21。但我还没有找到任何关于动态按钮的教程设计.

我正在创建时事件中执行所有操作。我无法在创建事件之外编写代码,也无法针对我所处的这种特殊情况使用任何 XML。

这是输出:

代码如下:

android.graphics.drawable.GradientDrawable gd_btone = new android.graphics.drawable.GradientDrawable();

gd_btone.setCornerRadius(4);
gd_btone.setStroke(2, Color.parseColor("#ffffff"));
gd_btone.setColor(Color.parseColor("#232323"));

android.graphics.drawable.RippleDrawable ripdr = new android.graphics.drawable.RippleDrawable(new android.content.res.ColorStateList(new int[][]{new int[]{}}, new int[]{ Color.parseColor("#888888")}), gd_btone, null);

button1.setBackground(ripdr);
button2.setBackground(ripdr);
button3.setBackground(ripdr);
button4.setBackground(ripdr);

此外,任何人都可以帮助我使这段代码与 api 级别 8 向后兼容,以及如何在此 drawable 上设置边距? 我不是 Android 开发人员,所以我对此了解不多。

我看到滴水效果应用于最后一个按钮,即使单击其他按钮也是如此。因此,我认为 RippleDrawable class 不支持您正在寻找的那种行为;单个实例一次只能绑定到一个按钮。

我建议只创建四个单独的 RippleDrawable 实例。

免责声明:我没有使用过 RippleDrawables,但这完全基于您提供的输出和 Android 开发的个人经验。