从父自定义viewGroup设置子参数

时间:2018-02-06 14:14:45

标签: android android-layout android-custom-view android-theme android-styles

我有一个带有xml的CustomViewGroup,如下所示:

<?xml version="1.0" encoding="utf-8"?>
 <merge xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:layout_width="wrap_content"
 android:layout_height="match_parent"
 android:gravity="center"
 android:orientation="horizontal">         

 <View      
  android:layout_width="?"     
  android:layout_height="?"
  android:id="@+id/child"
  />

</merge>

我希望像这样使用父母

 <CustomViewGroup
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/parent"
    app:itemWidth="30dp"
    app:itemHeight="30dp"
    />

如您所见,我想从父属性中读取子宽度和高度。有可能吗?
类似的东西,从父主题中读取吧?当您从父主题设置类似项目背景的值时。

 android:background="?attr/selectableItemBackground"

1 个答案:

答案 0 :(得分:0)

是的,这是可能的。这是CustomViewGroup所需的Java代码......真的不错:

public class CustomViewGroup extends FrameLayout {

    private static final int DEFAULT_CHILD_WIDTH_PX = 48;
    private static final int DEFAULT_CHILD_HEIGHT_PX = 48;

    public CustomViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray a = getResources().obtainAttributes(attrs, R.styleable.CustomViewGroup);
        int childWidthPx = a.getDimensionPixelSize(R.styleable.CustomViewGroup_itemWidth, DEFAULT_CHILD_WIDTH_PX);
        int childHeightPx = a.getDimensionPixelSize(R.styleable.CustomViewGroup_itemHeight, DEFAULT_CHILD_HEIGHT_PX);
        a.recycle();

        inflate(context, R.layout.custom_view_group, this);
        View child = findViewById(R.id.child);

        LayoutParams params = (LayoutParams) child.getLayoutParams();
        params.width = childWidthPx;
        params.height = childHeightPx;

        child.setLayoutParams(params);
    }
}

为了支持这一点,您必须在CustomViewGroup中为res/values/attrs.xml声明可设置样式的属性:

<resources>
    <declare-styleable name="CustomViewGroup">
        <attr name="itemWidth" format="dimension"/>
        <attr name="itemHeight" format="dimension"/>
    </declare-styleable>
</resources>

这是我用于custom_view_group.xml的布局。请注意,当您只有一个孩子时,无需使用<merge>标记:

<View
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/child"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="#caf"/>

从那里,您可以在任何其他布局中使用CustomViewGroup,并直接指定子视图的大小:

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.example.stackoverflow.CustomViewGroup
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_gravity="center"
        android:background="#eee"
        app:itemWidth="100dp"
        app:itemHeight="100dp"/>

</FrameLayout>

enter image description here

相关问题