Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom View without requiring layout_width in xml

Android SDK has TableLayout container:

 <TableLayout
    android:id="@+id/tablelayout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <TableRow>
        <TextView
            android:text="Some text"
            android:padding="3dip" />
    </TableRow>
</TableLayout>

TableLayout has layout_width and layout_height. Almost every View needs to specify the layout_width and layout_height in xml. But the TableRow does not require it.

I want to create Layout(extended from FrameLayout) which elements will not require layout_width and layout_height (I will calculate the size internally with some magic).

How can I remove the layout_width/layout_height requirement from xml for my custom view?

like image 943
Владимир Широков Avatar asked Oct 19 '25 05:10

Владимир Широков


1 Answers

To my knowledge those attributes are required by the tooling, and exceptions are made for certain framework widgets like TableLayout and TableRow in the tooling itself. This may have to do with the way these widgets generate LayoutParams for their children; normally the lack of layout_width or layout_height would cause an exception at runtime, but both of these widgets override setBaseAttributes() in their respective LayoutParams classes to not throw the exception and instead set a value like MATCH_PARENT.

You can try doing the same, but I expect the build tools will still produce a warning or error if you don't provide those attributes in your XML. Maybe there's a way to suppress that, but I don't think you could suppress it only for child views of your custom ViewGroup, so honestly I wouldn't go through the trouble if I were you.

Nothing says you have to respect the width and height given in XML, you can still do whatever "magic" you want, you just might break expectations if you decide to make your custom ViewGroup available to other developers.

like image 67
Karakuri Avatar answered Oct 21 '25 18:10

Karakuri