Android 以selectableItemBackground为背景的可绘制形状
我有几个按钮,我需要一个椭圆形的边框 所以我把它放在capsule_border.xml中Android 以selectableItemBackground为背景的可绘制形状,android,android-layout,android-view,android-drawable,android-selector,Android,Android Layout,Android View,Android Drawable,Android Selector,我有几个按钮,我需要一个椭圆形的边框 所以我把它放在capsule_border.xml中 <?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <corners android:radius="9999dp"/> <stroke android:width="1px
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="9999dp"/>
<stroke
android:width="1px"
android:color="@color/border_gray" />
</shape>
我会在需要的地方使用android:background=“@drawable/capsule\u border.xml
现在,我想有一个按钮,有这个椭圆形的边框,还有一个android:background=“?selectableItemBackground”
用于视觉反馈
我尝试使用一个带有selectableItembackground的父布局和带有capsule_边框的按钮。但是,看起来突出显示的可单击区域是整个正方形,而不仅仅是capsule边框内的区域
是否有某种方法可以使selectableItemBackground不在视图的整个矩形中占据很高的位置,而只在我绘制的边框内?具有圆角。xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@android:color/transparent"/>
<corners android:radius="15dp" />
<stroke
android:width="1px"
android:color="#000000" />
</shape>
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?android:attr/colorControlHighlight">
<item android:id="@android:id/mask">
<shape android:shape="rectangle">
<solid android:color="#000000" />
<corners android:radius="15dp" />
</shape>
</item>
<item android:drawable="@drawable/round_corners" />
</ripple>
和my_ripple.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@android:color/transparent"/>
<corners android:radius="15dp" />
<stroke
android:width="1px"
android:color="#000000" />
</shape>
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?android:attr/colorControlHighlight">
<item android:id="@android:id/mask">
<shape android:shape="rectangle">
<solid android:color="#000000" />
<corners android:radius="15dp" />
</shape>
</item>
<item android:drawable="@drawable/round_corners" />
</ripple>
和按钮:
<Button
android:background="@drawable/my_ripple"
... />
这将导致:
参见文章。我对第一个答案有一个更简单的版本:
仅将其作为背景应用,但如果阴影应用于
按钮
,请记住移除阴影:
style=“?无边框按钮样式”
祝你好运
在2020年,这里有一个更简单的解决方案(API>=21,因为我们使用的是
?attr
语法):
这真的很好。如果有一个什么是这个解决方案的最低android版本会更好吗?@Zhen Liu我没有看到任何API级别的要求在下降,我想这对所有版本都是好的。这种方法是可行的,但它有一个问题,它总是绘制背景色(在这种情况下为白色)当项目未点击时。这会导致透支。另一方面,使用遮罩,我们可以有一个默认的透明背景,并避免透支。