Aaron Warnecke
Aaron Warnecke

Reputation: 171

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

Upvotes: 2

Views: 1727

Answers (4)

Mo Faizan Shaikh
Mo Faizan Shaikh

Reputation: 307

  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.

Upvotes: 0

Gabe Sechan
Gabe Sechan

Reputation: 93561

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.

Upvotes: 2

Rasel
Rasel

Reputation: 5734

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"/>

Upvotes: 2

Lakhwinder Singh
Lakhwinder Singh

Reputation: 7209

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"/>

Upvotes: 0

Related Questions