【发布时间】:2017-06-28 12:59:12
【问题描述】:
我有以下自定义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>
这种方法存在多个问题:
-
背景形状完全被波纹覆盖,不再可见(无论是否选中)
背景形状应该保持不变,我只想在单击按钮时添加波纹效果(选中或未选中)
-
涟漪效果的半径太大,它们相互重叠
波纹半径应该和我的按钮半径一样。
我不知道如何进行这项工作,非常感谢任何建议。
【问题讨论】:
-
您是否尝试过自己添加波纹选择器但作为前景属性?
-
@ditn 是的,我有。
setForeground()仅适用于 API 23+,因此我创建了一个仅包含CustomCompoundButton的布局 XML。将其android:foreground属性设置为波纹并从代码中对其进行膨胀。Button看起来很好,但波纹根本没有出现。
标签: android android-layout android-drawable