安卓给相对布局RelativeLayout增加一个通用遮罩层

效果图

解决方案

  • 关键代码
    对RelativeLayout增加一个函数扩展
/**
 * 针对RelativeLayout,显示或隐藏一个遮罩层
 * 注意点:不能在onCreate、onViewCreated等界面初始化函数中调用,必须在页面初始化后调用。
 * 因为涉及到设置遮罩层的宽度和高度,如果界面未初始化完成,其宽和高都没有固定。
 * shouldShow:是否显示遮罩层
 * maskColor:遮罩层颜色
 */
fun RelativeLayout.showMaskLayer(shouldShow: Boolean = true, maskColor: String = "#807F7F7F") {
    val maskViewTag = "MASK_VIEW_TAG"
    var maskView = findViewWithTag<View>(maskViewTag)
    if (shouldShow) {
        if (maskView == null) {
            maskView = View(context)
            maskView.tag = maskViewTag
            //设置遮罩层颜色
            maskView.setBackgroundColor(Color.parseColor(maskColor))
            //屏蔽点击事件
            maskView.setOnClickListener { }
            addView(maskView, width, height)
        }
    } else {
        maskView?.let { removeView(it) }
    }
}
  • 使用样例
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        showBtn.setOnClickListener {
            relativeLayout.showMaskLayer(true)
        }
        hideBtn.setOnClickListener {
            relativeLayout.showMaskLayer(false)
        }

    }
}

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/relativeLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!" />
    </RelativeLayout>

    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp">

        <RadioButton
            android:id="@+id/showBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="显示遮罩" />

        <RadioButton
            android:id="@+id/hideBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="隐藏遮罩" />
    </RadioGroup>
</LinearLayout>

完整源代码

https://gitee.com/cxyzy1/maskLayer

发布了407 篇原创文章 · 获赞 90 · 访问量 39万+

猜你喜欢

转载自blog.csdn.net/yinxing2008/article/details/104165806