我正在尝试在我的活动上绘制位图,显示按钮作为叠加层就像魅力,但我不能处理位图。我应该在代码中更改什么? 我试图通过onCreate()中的mView.invalidate()手动调用onDraw,但它不起作用。 提前谢谢!
package com.example.btserver
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.IBinder;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
public class HUD extends Service implements OnTouchListener {
Button mButton;
OverlayView mView;
@Override
public IBinder
onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mView = new OverlayView(this);
mButton = new Button(this);
mButton.setText("Overlay button");
mButton.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
setText();
return true;
}
});
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,//TYPE_SYSTEM_ALERT,//TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE |
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN, //will cover status bar as well!!!
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.LEFT | Gravity.TOP;
params.y = 100;
params.x = 100;
params.setTitle("Load Average");
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(mButton, params);
wm.addView(mView, params);
}
@Override
public void onDestroy() {
super.onDestroy();
if(mButton != null)
{
((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(mButton);
mButton = null;
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
Toast.makeText(this,"Overlay button event", Toast.LENGTH_SHORT).show();
return false;
}
public void setText() {
Toast.makeText(this,"Overlay button event", Toast.LENGTH_SHORT).show();
}
}
class OverlayView extends ViewGroup {
private Paint mLoadPaint;
Bitmap cursor;
public int x = 0,y = 0;
public void Update(int nx, int ny) {
x = nx; y = ny;
}
public OverlayView(Context context) {
super(context);
cursor = BitmapFactory.decodeResource(context.getResources(), R.drawable.cursor);
mLoadPaint = new Paint();
mLoadPaint.setAntiAlias(true);
mLoadPaint.setTextSize(10);
mLoadPaint.setARGB(255, 255, 0, 0);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(cursor, 0,0, mLoadPaint);
}
@Override
protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
}