如何使带Drawable的View背景完全透明且不继承父布局颜色?
解决ConstraintLayout内透明控件仍显示父布局颜色的问题
我帮你分析下问题所在哈:首先得澄清一个概念——@android:color/transparent本身就是完全透明的,它的作用就是让下层的内容透出来,所以你看到父布局的颜色是正常的,这不是“继承”,而是透明背景的特性。
如果你只是想让这个矩形控件完全不绘制属于自己的背景(比如之前控件有默认背景,现在想清空),直接把它的background设为@null就可以了:
<View android:id="@+id/your_rect_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@null" <!-- 其他约束属性 --> app:layout_constraintXXX="..." />
但如果你的需求是让这个矩形区域透出父布局之外的内容(比如Activity的背景色、壁纸,而不是ConstraintLayout本身的背景),那上面的方法就没用了——因为ConstraintLayout的背景本来就在子控件下面,子控件透明只会透出父布局的颜色。这时候得换个思路,给父布局做“镂空”处理:
方法1:用LayerList创建带镂空的背景
先在drawable目录下创建一个constraint_bg_with_hole.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 第一层:父布局原本的背景色 --> <item android:drawable="@color/your_parent_bg_color" /> <!-- 第二层:带透明镂空的遮罩,还可以加边框 --> <item> <shape android:shape="rectangle"> <solid android:color="@android:color/transparent" /> <!-- 通过padding控制镂空区域的位置和大小 --> <padding android:left="60dp" android:top="60dp" android:right="60dp" android:bottom="60dp" /> <!-- 如果需要给镂空区域加边框的话 --> <stroke android:width="1dp" android:color="@color/your_border_color" /> </shape> </item> </layer-list>
然后把ConstraintLayout的背景换成这个drawable:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/constraint_bg_with_hole"> <!-- 这里不需要再放那个透明矩形控件了,背景已经实现了镂空效果 --> </android.support.constraint.ConstraintLayout>
方法2:用代码动态裁剪父布局(适合需要调整镂空位置的场景)
如果需要动态控制镂空区域的大小或位置,可以通过ViewOutlineProvider来裁剪ConstraintLayout:
val parentLayout = findViewById<ConstraintLayout>(R.id.your_parent_constraint) parentLayout.outlineProvider = object : ViewOutlineProvider() { override fun getOutline(view: View, outline: Outline) { // 父布局的整体范围 val parentRect = Rect(0, 0, view.width, view.height) // 要镂空的矩形区域(坐标相对于父布局) val holeRect = Rect(100, 100, 400, 400) val path = Path().apply { // 添加父布局的完整矩形 addRect(parentRect.toRectF(), Path.Direction.CW) // 添加镂空的矩形 addRect(holeRect.toRectF(), Path.Direction.CW) // 用奇偶填充模式实现镂空 fillType = Path.FillType.EVEN_ODD } outline.setConvexPath(path) } } // 开启裁剪效果 parentLayout.clipToOutline = true
另外还要检查下你的矩形控件是不是自定义控件,如果是,可能它自带默认背景,这时候设@null才能彻底清除哦。
内容的提问来源于stack exchange,提问作者ltalhouarne
相关产品推荐
相关产品推荐

