The problem:
Add dynamically checkboxes to the LinearLayout. Current range of child views 2-7, but quantity is not limited.
My first approach was pure in the code:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
for (String answer : generateAnswers()) {
CheckBox checkBox = new CheckBox(getContext());
checkBox.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
checkBox.setGravity(Gravity.CENTER);
checkBox.setText(answer);
mvAnswersLayout.addView(checkBox, lp);
}
Feels like CheckBox item should live in a xml, so second variant:
LayoutInflater inflater = LayoutInflater.from(getActivity());
for (String answer : generateAnswers()) {
View v = inflater.inflate(R.layout.answer_item, mvAnswersLayout, true);
CheckBox checkBox = (CheckBox) v.findViewById(R.id.checkbox_id);
checkBox.setText(answer);
checkBox.setId(General.generateViewId());
}
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBox
android:id="@+id/checkbox_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="17sp"
android:padding="4dp"
/>
</merge>
To eliminate redundant viewgroup I use tag <merge>
and utility View.generateViewId().
Seems the second approach is the way every android developer would expect. But what bothers me is hitting findViewById()
multiple times (every next one will be a bit slower).
Any pros and cons?