我正在尝试向框架布局添加多个自定义视图,但是它始终占用框架布局的整个宽度和高度。自定义视图仅包含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。
答案 0 :(得分:0)
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的此实现。