How to create an overlay that blocks touch events

2020-05-27 10:32发布

I used a layer of framelayout with a semi-translucent background to create an overlay. But this overlay doesn't block touch events to interact with the views below it. How should create an overlay that blocks all touch events?

5条回答
Luminary・发光体
2楼-- · 2020-05-27 11:08

If overlay doesn't get touch events, then the events are passed to underlying view, so to block touch events in views below it, make your overlay touchable. android:clickable="true"

查看更多
地球回转人心会变
3楼-- · 2020-05-27 11:09

Improving the Blesson Jose answer, you need set the android:focusable="true" and android:clickable="true" if you are using View to block the touch.

查看更多
Fickle 薄情
4楼-- · 2020-05-27 11:13

put the button on overlay layer.then set that button android:background="@null" it block touch event of view below it..hope it solve your problem

查看更多
聊天终结者
5楼-- · 2020-05-27 11:34

Following code will add overlay on top of everything :

View v1 = new View(this);    
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
 1000,
 50,
 WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
 WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
 PixelFormat.OPAQUE);

params.gravity = Gravity.BOTTOM;
WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
wm.addView(v1, params);

to block the touch event either you have to change the flag or below code will work:

protected boolean onTouchEvent (MotionEvent me) {
    return true;
}

For v1 you would do an import:

import android.view.View.OnTouchListener;

Then set the onTouchListener:

v1.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return true;
    }
})
查看更多
太酷不给撩
6楼-- · 2020-05-27 11:34

Below code has worked for me. I've added android:clickable="true" to block touch events to other views below it.

This is an example with a ProgressBar inside the overlay. If you don't want the ProgressBar, you can use the FrameLayout without it.

<FrameLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/progress_overlay"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:alpha="0.4"
            android:animateLayoutChanges="true"
            android:background="@android:color/black"
            android:visibility="gone"
            android:clickable="true">

            <ProgressBar
                style="?android:attr/progressBarStyleLarge"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:indeterminate="true"/>

</FrameLayout>
查看更多
登录 后发表回答