0

I've created a custom ViewGroup that contains arbitrary child Views and it is expected to populate them. It needs to know the ids of it's children, so I defined an array of ids in arrays.xml and I'm passing that array as an attribute to my custom group, like this:

my_layout.xml:

    <com.example.MyLayout
            ...
            custom:children="@array/four_children">

            <TextView ...
                    android:id="@+id.child1" />

            <TextView ...
                    android:id="@+id.child2" />

            <TextView ...
                    android:id="@+id.child3" />

            <TextView ...
                    android:id="@+id.child4" />

    </com.example.MyLayout>

arrays.xml:

<array name="four_children">
    <item>@id/child1</item>
    <item>@id/child2</item>
    <item>@id/child3</item>
    <item>@id/child4</item>
</array>

I chose this approach because one of the design goals was to define the layouts entirely in xml.

Basically my question is, is using an array of View ids like this an anti-pattern or otherwise dangerous?

1 Answer 1

1

The main thing I don't like about it is that you have the same data in two places (in the id array and in the child views themselves). You will need to keep the two versions in sync to avoid problems. The problem is aggravated by having the two data sets in different files.

Without knowing more about what you're doing, it's hard to suggest an alternative approach, but I would recommend finding one. Couldn't you just iterate through the children after you inflate the custom layout and collect the IDs? (You would do this in onFinishInflate, so the children would have also been inflated.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.