Android 4.x - System Overlay - Cannot capture touch events

家住魔仙堡 提交于 2019-12-24 03:41:32

问题


I am trying to create a simple overlay app for Android 4.4.

I have found an example to draw a button over the screen, all works fine but the touch event listener is not firing.

import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;

public class HUD extends Service {
    Button mButton;

    @Override
    public IBinder
    onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //mView = new HUDView(this);
        mButton = new Button(this);
        mButton.setText("My Overlay Button");
        mButton.setClickable(true);
        mButton.setOnTouchListener(new View.OnTouchListener() {
          @Override
          public boolean onTouch(View arg0, MotionEvent arg1) {
            mButton.setText("CLICKED!!!");
            return true;
          }
        }); 

        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.RIGHT | Gravity.CENTER;
        params.setTitle("Load Average");
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        wm.addView(mButton, params);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mButton != null)
        {
            ((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(mButton);
            mButton = null;
        }
    }
}

What am i doing wrong?


回答1:


Seems like you rather need an OnClickListener instead of an OnTouchListener for your button.




回答2:


Use WindowManager.LayoutParams.TYPE_SYSTEM_ALERT to make the view clickable in 4.3.

TYPE_SYSTEM_OVERLAY no longer allows clicks.



来源:https://stackoverflow.com/questions/20838711/android-4-x-system-overlay-cannot-capture-touch-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!