Как динамически добавлять кнопки для просмотра, чтобы ширина макета работала правильно? - PullRequest
0 голосов
/ 26 сентября 2018

Я пытаюсь динамически добавить несколько кнопок, точнее ToggleButtons, в вид.Если я представляю кнопки непосредственно в XML, они отображаются правильно при отображении.Но когда одни и те же кнопки надуваются из xml и вставляются с помощью addView (View, index), я получаю другое представление при рисовании действия.

Ниже приведены два снимка экрана.Я пытаюсь программно воспроизвести то, что вы видите в первом, но получаю второе.Обратите внимание, что в LinearLayout, к которому добавляются объекты ToggleButton, уже есть два объекта View, каждый из которых имеет желтый цвет фона, и между ними вставляются кнопки переключения.Объекты View обычно невидимы и необходимы, поэтому я могу определить расстояние на концах в процентах, следовательно, 0dp layout_width.

xml и код также приведены ниже.Почему экраны не отображаются одинаково, так как в обоих случаях я использую один и тот же xml?Любая помощь приветствуется, так как я должен добавить эти кнопки программно, так как их количество неизвестно во время выполнения (управляемое json, с сервера).

Что отображается, когда 4 кнопки переключения определены в xml между2 (желтый) Просмотр объектов:

enter image description here

Но когда 4 кнопки переключения программно вставляются между двумя (желтыми) объектами просмотра:

enter image description here

XML для экрана, который правильно отображает (по желанию):

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center"
    android:id="@+id/linLytRubCard"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dp"
        android:background="@color/ail_blue"
        >

        <ImageButton
            android:id="@+id/btnExpandDummy"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".10"
            android:padding="5dp"
            android:background="?android:attr/selectableItemBackground"
             />

        <TextView
            android:id="@+id/tvCardTitle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".80"
            android:textColor="@color/black"
            android:textSize="16sp"
            android:gravity="center"
            android:layout_gravity="center_vertical"
            android:text="This-is-title"
            />

        <ImageButton
            android:id="@+id/btnExpandCollapse"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".10"
            android:padding="5dp"
            android:background="?android:attr/selectableItemBackground"
            android:src="@drawable/down_arrow_expand_rubric" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dp"
        android:id="@+id/linlytSegControl"
        >

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight=".10"
            android:background="@color/yellow"
            />

        <ToggleButton
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".20"
            android:gravity="center"
            android:paddingTop="8dp"
            android:paddingBottom="8dp"
            android:textOn="0"
            android:textOff="0"
            android:text="0"
            android:textSize="16dp"
            android:checked="false"
            android:background="@drawable/selector_leftmost_button_state"
            />

        <ToggleButton
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".20"
            android:gravity="center"
            android:paddingTop="8dp"
            android:paddingBottom="8dp"
            android:textOn="2"
            android:textOff="2"
            android:text="2"
            android:textSize="16dp"
            android:background="@drawable/selector_middle_button_state"
            android:checked="false"
            />

        <ToggleButton
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".20"
            android:gravity="center"
            android:paddingTop="8dp"
            android:paddingBottom="8dp"
            android:textOn="3"
            android:textOff="3"
            android:text="3"
            android:textSize="16dp"
            android:background="@drawable/selector_middle_button_state"
            android:checked="false"
            />

        <ToggleButton
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".20"
            android:gravity="center"
            android:paddingTop="8dp"
            android:paddingBottom="8dp"
            android:textOn="4"
            android:textOff="4"
            android:text="4"
            android:textSize="16dp"
            android:checked="false"
            android:background="@drawable/selector_rightmost_button_state"
            />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight=".10"
            android:background="@color/yellow"
            />

    </LinearLayout>

Я создаю и добавляю кнопки переключения в цикле так:

LinearLayout linLytSegCtrl = (LinearLayout) this.findViewById(R.id.linlytSegControl);

for (int x = 0; x < m_arrRubItemPointVals.size(); x++)
{
    ToggleButton tbn = (ToggleButton) View.inflate(m_context, R.layout.segmented_button_rubric, null);

    String sTitle = String.valueOf(x);
    tbn.setText(sTitle);
    tbn.setTextOn(sTitle);
    tbn.setTextOff(sTitle);
    linLytSegCtrl.addView(tbn, x+1); // inserts AFTER first yellow View in xml and before the second one
}

XML для отдельных кнопок переключения, считываемых во время выполнения:

<ToggleButton
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight=".20"
    android:gravity="center"
    android:paddingTop="8dp"
    android:paddingBottom="8dp"
    android:textSize="16dp"
    android:background="@drawable/selector_middle_button_state"
    android:checked="false"
    />

Да, когда я вставляю кнопки во время выполнения, я удаляю их из xml и просто оставляю два объекта View.

1 Ответ

0 голосов
/ 26 сентября 2018

Возможно, вам нужно установить родителя в вашем вызове для view.inflate: View.inflate(m_context, R.layout.segmented_button_rubric, linLytSegCtrl);.

В документации для View.Inflate говорится, что третий параметр «Используется для правильного раздувания параметров layout_ *»: https://developer.android.com/reference/android/view/View.html#inflate(android.content.Context,%20int,%20android.view.ViewGroup)

...