我试图向框架布局添加多个自定义视图,但它总是占用框架布局的整个宽度和高度。自定义视图只包含一个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。
OverlayView的大小在onMeasure()中计算。试试这个实现:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int width = View.MeasureSpec.makeMeasureSpec(bitmap.getWidth(), MeasureSpec.EXACTLY);
int height = View.MeasureSpec.makeMeasureSpec(bitmap.getHeight(), MeasureSpec.EXACTLY);
setMeasuredDimension(width, height);
}
另请参阅onMeasure的此实现。