Android自定义蒙层

在开发过程中有时候会遇到特定情况下显示蒙层的需求,比如在点击某个Edittext搜索框时,部分界面出现浅透明蒙层:
在这里插入图片描述

自定义蒙层:

class MongolianView(context: Context, attrs: AttributeSet?):LinearLayout(context, attrs){

    var clickListener: (() -> Unit)? =null

    override fun dispatchDraw(canvas: Canvas?) {
        val paint= Paint()
        paint.color= Color.parseColor("#330C0B1C")
        canvas?.drawRect(0f,0f,width.toFloat(),height.toFloat(),paint)
        super.dispatchDraw(canvas)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        clickListener?.invoke()
        return true
    }
}

在xml布局中声明:

    <xxx.xxx.xxx.post.widget.MongolianView
        android:id="@+id/mongolian_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

在Activity中初始化蒙层点击事件监听:

mongolian_view.apply {
   clickListener={
      //...
   }
}