【歪门邪道】Android页面上快速实现蒙层引导需求

这篇博客分享了一种在Android中快速实现带挖孔的引导蒙层的方法,避免了使用三方库和硬编码布局。通过创建ShadowView类,程序员可以方便地为指定视图添加引导蒙层,适配不同设备,并在引导结束后轻松移除。代码简洁高效,适用于紧急项目中的快速实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这几年工作发现一个定律,新年前一定有一个大项目,项目优先度一定高,排期一定倒着排,程序员一定要加班。就好像,缺了这个项目,发年终奖就亏了一样。

新需求有多个引导蒙层,蒙层需要漏出被引导的按钮区域,时间上调研一下已有的三方控件来不及了,简单的写死位置难以适配多种机型,activity嵌套多个fragment的结构也不允许在布局文件内硬编码一个蒙层。

所以,只能用最短的方式写一个带挖孔的蒙层,配合引导图使用。

蒙层view代码

public class ShadowView extends View {

    Paint pRect = new Paint();
    private Rect mRect = new Rect();
    private View mView;
    private int[] location = new int[2];

    public ShadowView(Context context) {
        super(context);
        pRect.setColor(getResources().getColor(R.color.b_c0_64));
        pRect.setAntiAlias(true);
    }

    public ShadowView(Context context, @Nullable @org.jetbrains.annotations.Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public ShadowView(Context context, @Nullable @org.jetbrains.annotations.Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 引导区域View
     *
     * @param view
     */
    public void setView(View view) {
        mView = view;
    }

    /**
     * 设置引导区域
     *
     * @param rect
     */
    public void setRect(Rect rect) {
        mRect = rect;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (mView != null) {
            mView.getLocationInWindow(location);
            mRect.left = location[0];
            mRect.top = location[1];
            mRect.right = location[0] + mView.getMeasuredWidth();
            mRect.bottom = location[1] + mView.getMeasuredHeight();
        }

        if (mRect != null) {
            canvas.drawRect(0, 0, getWidth(), mRect.top, pRect);
            canvas.drawRect(0, mRect.bottom, getWidth(), getHeight(), pRect);
            canvas.drawRect(0, mRect.top, mRect.left, mRect.bottom, pRect);
            canvas.drawRect(mRect.right, mRect.top, getWidth(), mRect.bottom, pRect);
        }
    }
}

这样,简单的蒙层view就实现了。

这个蒙层可以通过传递view,或传递view相对于屏幕的位置(Rect),就能在对应的view上下左右各绘制一个黑色半透明蒙层,用的时候直接add到decor view 上就可以


            FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView();
            mShadowView = new ShadowView(this);
            frameLayout.addView(mShadowView);
            mShadowView.setView(targetView);

注意,引导结束后一定要移除shadowview哦。


            FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView();
            frameLayout.removeView(mShadowView);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值