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

1.4k views Asked by At

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

4

There are 4 answers

1
Rasel On BEST ANSWER

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"/>
0
Lakhwinder Singh On

Create a isolate xml file for your view that you want to use at many places. After that just use <include/> where you want to use that xml.

      <include
        android:id="@+id/toolbar"
        layout="@layout/common_tool_bar_layout" // your xml name
        app:layout_constraintEnd_toEndOf="parent"/>
0
Gabe Sechan On

For the loop, you're doing it at the wrong level. Create a custom view that extends whatever Layout class is most convenient (linear, frame, constraint, relative etc). In its constructor, loop creating the appropriate number of children and adding them to itself. Then include this class in your xml.

0
Mo Faizan Shaikh On
  1. You can use RecyclerView with GridLayoutManager for that purpose

  2. You can also add RadioButtons dynamically linearLayout.addView(radioButton);

Off course, method 1 is most preferred as it is good performance wise.