我正在尝试将多个自定义视图添加到框架布局,但它总是占用框架布局的整个宽度和高度。自定义视图只包含一个 50x50 的图像,我希望它能够在框架布局中移动,但由于自定义视图占据了整个空间并相互重叠,我无法选择其他自定义视图,因此我希望将其包裹起来。
这是我添加自定义视图的方式:
OverlayView overlayView = new OverlayView(EditorActivity.this, themeFilter.drawable);
frameLayout.addView(overlayView, 1, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT));
这是 OverlayView :
public class OverlayView extends View {
Bitmap bitmap;
float x,y;
float centerX, centerY;
public OverlayView(Context context, int drawable) {
super(context);
bitmap = BitmapFactory.decodeResource(context.getResources(), drawable);
centerX = (float)getWidth() /2;
centerY = (float)getHeight() /2;
x = centerX;
y = centerY;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (x != centerX && y != centerY) {
canvas.drawBitmap(bitmap, x-bitmap.getWidth()/2, y-bitmap.getHeight()/2, null);
} else {
//INITIALIZE BITMAP ON CENTER OF SCREEN
canvas.drawBitmap(bitmap, (float)getWidth()/2 - bitmap.getWidth()/2, (float)getHeight()/2 -bitmap.getHeight()/2, null);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN :
break;
case MotionEvent.ACTION_MOVE :
x = event.getX();
y = event.getY();
invalidate();
break;
case MotionEvent.ACTION_UP :
x = event.getX();
y = event.getY();
invalidate();
}
return true;
}
}
现在我在想的是保持原样。意思是,OverlayView 占据了整个屏幕,我只需要在其他 OverlayViews 之间切换焦点就可以移动它们(我什至不知道这是否可能——在堆叠的 OverlayViews 之间切换焦点)但我担心浪费的空间影响内存和性能,因为图像只有 50x50。