我创建了一个新视图(扩展了ImageView)并覆盖了onMeasure方法。
Xml代码:
<by.bsuir.klondike.mainCardsView
android:id="@+id/imageview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitEnd"
android:baselineAlignBottom="true"
android:src="@drawable/cardsmain"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
/>
起初我覆盖了像这样的方法
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
width = parentWidth/2;
height = 210*width/498;
this.setMeasuredDimension(width, height);
this.setLayoutParams(new *ParentLayoutType*.LayoutParams(width,height));
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
根据Android developer onMeasure电话两次。在它第一次调用时,我收到parentWidth == 480和parentHeight == 320.但在第二次调用时,我收到parentWidth == 240和parentHeight == 101。 事实证明,大小正在改变两次。 我使用bool标志解决了这个问题,只在第一次调用时更改了维度。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (flag){
flag=false;
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
width = parentWidth/2;
height = 210*width/498;
}
this.setMeasuredDimension(width, height);
}
但我认为这是一种错误的方式。 我该怎么办呢?