gpt4 book ai didi

android - 为自定义 CompoundButton 添加波纹效果

转载 作者:太空宇宙 更新时间:2023-11-03 10:35:59 26 4
gpt4 key购买 nike

我有以下自定义 CompoundButton:

public class CustomCompoundButton extends CompoundButton {

public CustomCompoundButton(Context context) {
this(context, null);
}

public CustomCompoundButton(Context context, AttributeSet attrSet) {
super(context, attrSet);
setup();
}

private void setup() {
setBackgroundResource(R.drawable.button_selector);
setGravity(Gravity.CENTER);
setClickable(true);
}
}

在将 Button 添加到布局后,我通过代码设置了它的宽度和高度:

button.getLayoutParams().width = myWidth;
button.getLayoutParams().height = myHeight;

button_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/button_checked"
android:state_checked="true" />
<item
android:drawable="@drawable/button_unchecked"
android:state_checked="false" />
</selector>

button_checked.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="?colorAccent" />
</shape>

button_unchecked.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke
android:width="2dp"
android:color="?colorAccent" />
</shape>

这按预期工作,Button 未选中时为空圆,选中时为实心圆。

问题是我无法在此行为之上添加涟漪效应。

我试过将 selector 包装在 ripple 标签中,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#ffffff">
<selector>
<item
android:drawable="@drawable/button_checked"
android:state_checked="true" />
<item
android:drawable="@drawable/button_unchecked"
android:state_checked="false" />
</selector>
</ripple>

这种方法存在多个问题:

  • 背景形状完全被波纹覆盖,它们不再可见(无论是否选中)

    背景形状应该保持不变,我只想在单击按钮(选中或未选中)时添加涟漪效果

  • 涟漪效应的半径太大了,它们相互重叠

    波纹半径应与我的按钮的半径相同。

我不知道如何进行这项工作,非常感谢任何建议。

最佳答案

将每个 shape 包装在它自己的 ripple 中,而不是将整个 selector 包装在 ripple 中将具有想要的效果。

参见 this comment举个例子。

因此,button_unchecked.xml 看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:color="#ffffff"
tools:targetApi="lollipop">
<item android:id="@android:id/mask">
<shape android:shape="oval">
<stroke
android:width="2dp"
android:color="?colorAccent" />
</shape>
</item>
<item
android:id="@android:id/background"
android:drawable="?colorAccent" />
</ripple>

关于android - 为自定义 CompoundButton 添加波纹效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44803214/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com