Adding Checkboxes Dynamically To BottomSheetDialog: SetMargins() And SetPadding() Not Working As Expected
I want to add checkboxes dynamically to a BottomSheetDialog. However, the buttons are not aligning as I want them to. Styling the checkboxes works if I style them directly on the X
Solution 1:
Because in xml file you use dp
unit but in code you use pixel
unit. You must convert from dp to pixel before set margin for checkbox.
LinearLayout mainLinearLayout = bottomSheetDialog.findViewById(R.id.id_layout_bottom_sheet_choices);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
// margin-left: 10, margin-bottom: 10, like the margins in the two hardcoded xml checkboxes
int margin = (int)convertDpToPixel(10F, this);
params.setMargins(margin, 0, 0, margin);
for (int i = 0; i < answerChoices.size(); i++) {
CheckBox checkBox = new CheckBox(getContext());
checkBox.setText(answerChoices.get(i));
// left padding
checkBox.setPadding(margin, 0, 0, 0);
// i + 3 since there's already a textview and two sample checkboxes added, and i want to add the new checkbox after them and before the remaining elements
mainLinearLayout.addView(checkBox, i + 3, params);
}
// Add this method to convert dp to pixel
public static float convertDpToPixel(float dp, Context context){
return dp * ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}
Post a Comment for "Adding Checkboxes Dynamically To BottomSheetDialog: SetMargins() And SetPadding() Not Working As Expected"