androidxmlclassandroid-layoutandroid-components

Can I create a reusable component in an Android XML layout?


This is a simple question of code efficiency, while I'm learning more about layouts. I'm creating a grid of checkboxes, and each one has the same attributes for the most part. Each checkbox has 8 attributes, 5 of which are the same for each one. Can I create a sort of custom checkbox class that I can re-use, drastically simplifying my XML file?

Bonus points: can I create a loop/array in my XML file so I don't have to code each box individually? I have 32 rows by 5 columns = 160 individual checkbox components.

app_screenshot code_screenshot


Solution

  • Style in values/styles.xml Add common rules in style

    <style name="MyCheckBoxStyle">
            <item name="android:layout_width">match_parent</item>
            <item name="android:layout_height">wrap_content</item>
            ....
    </style>
    

    Use like this-

    <CheckBox
    ..uncommon rules...
    style="@style/MyCheckBoxStyle"/>