我想創建一個自定義的LinearLayout(後來定製的ImageButton),可以採取百分比值基於其母公司的大小,而不管父類型(相對或線性)的大小的兩個維度。我正在關注這篇文章:How to size an Android view based on its parent's dimensions,這非常有幫助,但我有一個問題,那些答案沒有解決。定製的ViewGroup作品裏面的LinearLayout不RelativeLayout的
當我把我的自定義的LinearLayout另外的LinearLayout內,按預期工作的一切。我的自定義LinearLayout覆蓋了預期的空間(下例中爲父寬度的80%)。
但是如果我把它放在一個RelativeLayout的裏面,我的屏幕上始終顯示爲空,我不知道爲什麼會這樣。
這裏是我的類:
public class ButtonPanel extends LinearLayout {
public ButtonPanel(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int newWidth = (int) Math.ceil(parentWidth * 0.8);
this.setMeasuredDimension(newWidth, parentHeight);
this.setLayoutParams(new RelativeLayout.LayoutParams(newWidth,parentHeight));
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
這裏是我的活動測試佈局。
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.android.tests.views.ButtonPanel
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/inner_panel"
android:gravity="center_horizontal"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true">
</com.android.tests.views.ButtonPanel>
</RelativeLayout>
在我的活動中,我所做的就是將內容視圖設置爲上述佈局。
(順便說一句,是否有人現在我怎麼能拿父母的類型動態地設置新LayoutParameters?上面你會看到父類型(RelativeLayout的)硬編碼到自定義視圖onMeasure功能)
在此先感謝您的幫助!
我不確定你的意思。 不可否認,我正在實現這個半盲,我從那一行了解到的是任何給定View或Viewgroup所具有的佈局參數,它們必須是其父容器的佈局參數的一個實例。 這是關於這一行,我在最後問了我的小問題,這樣我就不必將RelativeLayout作爲父類型進行硬編碼。 雖然,blessenm似乎給了我答案。 – RobertoCuba