自定义在LinearLayout填充空间中查看

时间:2014-08-21 21:47:49

标签: android android-layout

我通过继承View来使用自定义视图MaskCustomView。自定义视图的宽度/高度布局参数都是WRAP_CONTENT。

LinearLayout中的自定义视图占用了所有空间。我可以看到使用uiautomatorViewer:

image here

代码是:

public class MaskImageView extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mask_image);

    LinearLayout container = (LinearLayout) findViewById(R.id.maskID);

    MaskCustomView maskView = new MaskCustomView(this);
    maskView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    container.addView(maskView);
}


public class MaskCustomView extends View {

    private Bitmap bp;
    private Paint p;

    public MaskCustomView(Context context) {
        super(context);

        bp = BitmapFactory.decodeResource(getResources(), R.drawable.apple);
        p = new Paint();

    }



    @Override
    public void onDraw(Canvas canvas) {
        canvas.drawBitmap(bp, 0, 0 , p);
        super.onDraw(canvas);

    }

}
}

xml layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:id="@+id/maskID"
          android:layout_width="match_parent"
          android:layout_height="match_parent">

不应该只包装内容而不是在整个空间中使用高度和宽度吗?

1 个答案:

答案 0 :(得分:5)

尝试使MaskCustomView覆盖onMeasure

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if(bp == null) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    } else {
        setMeasuredDimension(MeasureSpec.makeMeasureSpec(bp.getWidth(), MeasureSpec.MODE_CONSTANT), MeasureSpec.makeMeasureSpec(bp.getHeight(), MeasureSpec.MODE_CONSTANT);
    }    
}