问题
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