自定义视图(扩展LinearLayout)“减肥”属性

时间:2014-11-26 18:52:19

标签: android android-layout android-custom-view android-layout-weight

所以..我正在定义一个如下所示的自定义视图/布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="3">

<Button
    android:id="@+id/option_a"
    style="?android:selectableItemBackground"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="One"
    android:background="?android:selectableItemBackground"
    android:textAppearance="?android:attr/textAppearanceButton"
    android:textColor="@android:color/secondary_text_dark" />

<Button
    android:id="@+id/option_b"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Two"
    android:background="?android:selectableItemBackground"
    android:textColor="@android:color/holo_red_dark"
    android:textAppearance="?android:attr/textAppearanceButton" />

<Button
    android:id="@+id/option_c"
    style="?android:selectableItemBackground"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Three"
    android:background="?android:selectableItemBackground"
    android:textAppearance="?android:attr/textAppearanceButton"
    android:textColor="@android:color/secondary_text_dark" />

</LinearLayout>

结果:

enter image description here

然后我将自定义视图添加到另一个布局中,如下所示:

<com.xxx.xxx.xxx.ThreeStatePreference
    android:id="@+id/mode"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

结果:

enter image description here

看起来这完全忽略了&#34;体重&#34;属性。我做错了什么?


PD:我找到了一个代码解决方案:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int wspec = MeasureSpec.makeMeasureSpec(getMeasuredWidth()/getChildCount(), MeasureSpec.EXACTLY);
    int hspec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY);

    for(int i=0; i<getChildCount(); i++){
        View v = getChildAt(i);
        v.measure(wspec, hspec);
    }
}

但我想知道是否可以使用XML。

0 个答案:

没有答案