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次,儘管執行結果是我想要的。