0

我有一个需要看起来像这样的视图:

<ConstraintLayout android:id="@+id/wrapper">
    <ConstraintLayout android:id="@+id/wrapped">
        <ViewGroup/>
    </ConstraintLayout>
    <Button/>
</ConstraintLayout>

但我想在我的布局中使用这样的:

<CustomComponent>
    <ViewGroup/>
</CustomComponent>

所以基本上我想写一个CustomComponent来将它的子ViewGroup注入到带有id“wrapped”的ConstraintLayout中,在它下面添加一个按钮并将整个东西包装在“wrapper”ConstraintLayout中。

在像 React 这样的库中,这可以使用组合现有视图并向其添加功能的 HOC 来完成。但是在这里实现起来似乎并不那么直观。

我的方法是这样的:

class CustomComponent extends ConstraintLayout {
    public void init(Context context) {
        inflate(context, R.layout.wrapper, this);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        View child = getChildAt(1);
        removeView(child);
        ViewGroup wrapped= findViewById(R.id.wrapped);
        wrapped.addView(child);
    }
}

所以基本上 ViewGroup 是在最后添加的,所以我必须手动删除它,然后再将它添加到“包装的”ConstraintLayout。这似乎很浪费,甚至容易出错;有一个更好的方法吗?

4

0 回答 0