2

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

Aaron Warnecke
  • 171
  • 1
  • 1
  • 8
  • 1
    We use listview or recyclerview programmatically instead of too long xml which slow down app and use style if you really want to do as your way – Rasel Mar 02 '20 at 04:13

4 Answers4

2

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"/>
Rasel
  • 5,488
  • 3
  • 30
  • 39
2

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.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
0

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"/>
Lakhwinder Singh
  • 6,799
  • 4
  • 25
  • 42
0
  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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mo Faizan Shaikh
  • 307
  • 1
  • 4
  • 14