我试图制作一个浮动视图,用户可以在屏幕上拖动.
我们的想法是启动一项服务,然后在屏幕上膨胀视图.
但是有一个问题,而不是将事件属于自己,它需要所有用户输入事件.
这是我的代码:manifest.xml:
浮动视图可以拖动:
package com.example.floatandroidpractice; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.MotionEvent; import android.view.View; public class littleIconView extends View { private float viewX; private float viewY; private Paint mPaint; private Bitmap androidIcon; public littleIconView(Context context) { super(context); mPaint = new Paint(); mPaint.setColor(Color.BLACK); androidIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); } @Override public void onDraw(Canvas cvs) { cvs.drawBitmap(androidIcon, viewX - androidIcon.getWidth() / 2, viewY - androidIcon.getHeight() / 2, mPaint); } @Override public boolean onTouchEvent(MotionEvent event) { boolean touchedX = Math.abs(viewX - event.getX()) > androidIcon.getWidth(); boolean touchedY = Math.abs(viewY - event.getY()) > androidIcon.getHeight(); boolean isValidTouch = !touchedX && !touchedY; if (isValidTouch) { if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) { viewX = event.getX(); viewY = event.getY(); } invalidate(); return true; } else return false; } }
和服务:
package com.example.floatandroidpractice; import android.app.Service; import android.content.Intent; import android.graphics.PixelFormat; import android.os.IBinder; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; public class WalkingIconService extends Service { @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { littleIconView a = new littleIconView(getApplicationContext()); LayoutParams mLayoutParams = new WindowManager.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0, 0, PixelFormat.TRANSPARENT); WindowManager mWindowManager = (WindowManager) this.getSystemService(WINDOW_SERVICE); mLayoutParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_NOT_FOCUSABLE | LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | LayoutParams.FLAG_LAYOUT_INSET_DECOR | LayoutParams.FLAG_LAYOUT_IN_SCREEN; mWindowManager.addView(a, mLayoutParams); return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { return null; } }
完整项目:https://github.com/shanwu/shanwu_coding_base/tree/xxx/floatAndroidPractice