我正在为 android 使用库 OnBarCodeGenerate。这会在自定义视图中绘制条形码。我应该如何以占用所需空间的方式编写自定义视图的 onMeasure 方法。高度和宽度的行为与 wrap_content 相同。?
现在我的自定义视图的 onMeasure 方法如下。我必须在其中给出所需的宽度。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec,heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(),getMeasuredHeight());
int desiredWidth = 200 * (int)getResolution();
int desiredHeight = 200 * (int) getResolution();
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(widthSize, heightSize);
super.onMeasure(widthSize,heightSize);
int width;
int height;
//Measure Width
if (widthMode == MeasureSpec.EXACTLY) {
//Must be this size
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
width = Math.min(desiredWidth, widthSize);
} else {
//Be whatever you want
width = desiredWidth;
}
//Measure Height
if (heightMode == MeasureSpec.EXACTLY) {
//Must be this size
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
height = Math.min(desiredHeight, heightSize);
} else {
//Be whatever you want
height = desiredHeight;
}
//MUST CALL THIS
setMeasuredDimension(width,height);
}