2

好的,所以我正在尝试创建一些可重用的组件。基本上,我们有一个复合布局,包括:

-- 页眉
-- 描述
-- (任意数量的控件)
-- 页脚

所以我有一个自定义 ViewGroup 可以自动处理添加页眉和页脚,以及文本和其他变量的自定义属性。

这一切都很好,但我正在努力做到这一点,以便我可以在 XML 中指定控制视图(具有非常特定的布局),如下所示:

<com.mypackage.CustomLayout
    ///...
    >
    <com.mypackage.CustomControl
        //attributes
        />
    <com.mypackage.CustomControl2
        //attributes
        />
    <com.mypackage.CustomControl3
        //attributes
        />
</com.mypackage.CustomLayout>

对于我的自定义控件,它们都遵循以下一般模式:

示例布局 XML

<merge
    android:layout_width="match_parent"
    android:layout_height="100dp"
     //Attributes
    >
    <OtherView/>
    <OtherView/>
</merge>

对应的控制视图

public class ControlView extends LinearLayout {
    public ControlView (Context context) {
        super(context);
        init();
    }

    public ControlView (Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
        parseAttributes(attrs);
    }

    public ControlView (Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
        parseAttributes(attrs);
    }

    private void init () {
        LayoutInflater i = LayoutInflater.from(getContext());
        i.inflate(R.layout.example_layout, this);
        //Initialize subviews
    }
}

问题是合并标签中的参数被忽略了,我需要为每个自定义控件添加layout_width和参数,而不是使用合并标签中定义的布局参数。layout_height

如果我尝试在方法中设置 LayoutParams ,我仍然会得到一个运行时异常,init()说需要属性。layout_widthlayout_height

有没有更好的方法来做我正在做的事情?我只想为LayoutParams自定义控件的任何实例提供预设,而不管 XML 中提供了哪些参数(如果有)。

4

0 回答 0