Android CustomView from xml has a extra nesting ViewGroup

Issue

A simple CustomViewGroup is like this:

// kotlin
class MyLayout : ConstraintLayout {
    init{
        inflate(... R.layout.my_layout ...)
    }
}
<!-- my_layout.xml -->
<ConstraintLayout ...>
  <TextView .../>
  <Button .../>
</ConstraintLayout>

BUT, this is a problem. The layout levels is like this:

ConstraintLayout
    ConstraintLayout
        TextView
        Button

There is an extra nesting ConstraintLayout.

Is there any way to remove nested layouts?

There are some bad solutions´╝Ü

(1) Using <merge/>

Change xml like this:

<!-- my_layout.xml -->
<merge ...>
  <TextView .../>
  <Button .../>
</merge>

But the problem is it is inconvenient to make subsequent modifications to the xml.

(2) Change xml root to MyLayout.

<!-- my_layout.xml -->
<MyLayout ...>
  <TextView .../>
  <Button .../>
</MyLayout>

But the problem is you can only call MyLayout from LayoutInflater.inflate(R.layout.my_layout).

You can’t call MyLayout like new MyLayout(...) (for java) or <MyLayout .../> (for xml).

And it violates the principle of decoupling.

So, what is the best solution to remove extra nesting ViewGroup?

help~~~~~ ­čÖé

References

Update

Fixed – just like this:

    <merge
        tools:parentTag="android.widget.RelativeLayout"
        tools:layout_width="match_parent"
        tools:layout_height="match_parent"
    ... />

See:

Solution

Fixed – just like this:

    <merge tools:parentTag="android.widget.RelativeLayout"
        ...>
        <TextView .../>
        <Button .../>
    </merge>

Answered By – Fan Applelin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published