Динамическое добавление флажков в BottomSheetDialog: setMargins () и setPadding () не работают должным образом - PullRequest
0 голосов
/ 25 февраля 2019

Я хочу добавить флажки динамически в BottomSheetDialog.Однако кнопки не выравниваются так, как я хочу.Стилизация флажков работает, если я стилизую их непосредственно в XML, однако они не стилизуются вообще программно.

Вот мой код макета XML с двумя жестко заданными флажками:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/id_layout_bottom_sheet_choices"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#FFFFFF"
    android:orientation="vertical">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="start"
        android:padding="10dp"
        android:text="Escolha uma resposta"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#000000"
        android:layout_marginStart="10dp"
        android:layout_marginBottom="10dp"
        android:textSize="20sp"
        android:textStyle="bold" />

    <CheckBox
        android:id="@+id/checkBox2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginBottom="10dp"
        android:paddingLeft="10dp"
        android:text="CheckBox" />

    <CheckBox
        android:id="@+id/checkBox3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginBottom="10dp"
        android:paddingLeft="10dp"
        android:text="CheckBox" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="end"
        android:orientation="horizontal">

        <Button
            android:id="@+id/cancel_btn"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Cancelar" />

        <Button
            android:id="@+id/confirm_btn"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="OK" />
    </LinearLayout>
</LinearLayout>

ЗдесьЯ пытаюсь добавить больше из них программно:

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
params.setMargins(10, 0, 0, 10);

for (int i = 0; i < answerChoices.size(); i++) {
    CheckBox checkBox = new CheckBox(getContext());
    checkBox.setText(answerChoices.get(i));
    // left padding
    checkBox.setPadding(10,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);
}

Вот вывод в BottomSheetModal с этим кодом после добавления кнопок:

Как видите, первые жестко закодированные флажки выровнены правильно, однако два других флажка, добавленных с помощью кодирования, - нет.Даже цвета выбора флажка различны (но почему ???)

Вот вывод, который я притворяюсь (я жестко закодировал два других флажка, просто чтобы показать, как я хочу, чтобы вывод был после кодирования)

enter image description here

Как решить эту проблему?

1 Ответ

0 голосов
/ 25 февраля 2019

Потому что в XML-файле вы используете dp единицу, а в коде вы используете pixel единицу.Вы должны конвертировать из dp в пиксель перед установкой поля для флажка.

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);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...