CalendarBackground是一个自定义视图,它实现onDraw()和onMeasure()。它的大小是动态的,在onMeasure()中计算。设置一个按钮的大小accroding动态定制视图的大小
CalendarView是另一个自定义视图,它扩展了以下RelativeLayout。
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <lc.test.CalendarBackground android:id="@+id/calBg" android:layout_width="fill_parent" android:layout_height="wrap_content"/> <Button android:id="@+id/prevMonth" android:text="@string/prev_month" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </RelativeLayout>
按钮prevMonth的位置&大小应该由CalendarBackground来决定,所以我需要CalendarBackground.onMeasure后改变其大小()被调用。
我知道如何通过实际设置LayoutParams来改变按钮的大小,但我不知道应该在哪里放这些代码?它不能在CalendarView的构造函数中使用,因为在CalendarBackground.onMeasure()之前调用了代码...
非常感谢!
正如我不能回答我的问题,我在这里把答案:
我知道了。覆盖CalendarView类的onLayout方法,并在那里设置按钮的大小。
这是CalendarBackground.onMaesure的代码:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//Get canvas width and height
wCalendar = MeasureSpec.getSize(widthMeasureSpec);
hCalendar = 7*MeasureSpec.getSize(heightMeasureSpec)/10;
setMeasuredDimension(wCalendar, hCalendar);
}
这是CalendarView.onLayout代码:
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(prevMonth.getLayoutParams());
lp.width = (right - left)/7;
lp.height = (bottom - top)/7;
prevMonth.setLayoutParams(lp);
}
结果正是我想要的。这个onLayout在CalendarBackground.onMeasure()之后被调用。
但是,我观察到另一个问题。这就是执行顺序:然后是CanlendarBackground.onMaesure(),然后是另一个CalendarView.onLayout(),然后是CanlendarBackground.onDraw(),然后是CalendarView.onLayout(),然后是CalendarView.onLayout()的4次CanlendarBackground.onMaesure()。
我的代码有什么问题吗?我的意思是这个序列没有意义。 CanlendarBackground.onMaesure()被调用8次,而CalendarView.onLayout()被调用2次,尽管执行结果是我想要的。