java.lang.IllegalStateException в ScrollView при вращении устройства - PullRequest
0 голосов
/ 03 июня 2018

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

java.lang.IllegalStateException: ScrollView can host only one direct child

Я добавляю Фрагмент, когда элемент Spinner щелкается следующим образом:

fragmentView.removeAllViews();

FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
ConfigureFragment fragment = new ConfigureFragment();
fragment.setReferences(MainActivity.this, (Controller) spinner.getSelectedItem());
fragmentTransaction.add(fragmentView.getId(), fragment, "");
fragmentTransaction.commit();

Я использовалУдалитеAllViews, чтобы убедиться, что ScrollView пуст, прежде чем я добавлю что-то новое.Это файл макета для моего фрагмента:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ConfigureFragment">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:stretchColumns="0">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <EditText
                android:id="@+id/editTextName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:ems="10"
                android:gravity="center"
                android:inputType="textPersonName"
                android:padding="10dp" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="@string/esp_channel" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <SeekBar
                android:id="@+id/seekBarRed"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:max="@integer/esp_value_max"
                android:progress="@integer/esp_value_min" />

            <EditText
                android:id="@+id/editTextRed"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:ems="10"
                android:inputType="number"
                android:padding="10dp" />

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <SeekBar
                android:id="@+id/seekBarGreen"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:max="@integer/esp_value_max"
                android:progress="@integer/esp_value_min" />

            <EditText
                android:id="@+id/editTextGreen"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:ems="10"
                android:inputType="number"
                android:padding="10dp" />

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <SeekBar
                android:id="@+id/seekBarBlue"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:max="@integer/esp_value_max"
                android:progress="@integer/esp_value_min" />

            <EditText
                android:id="@+id/editTextBlue"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:ems="10"
                android:inputType="number"
                android:padding="10dp" />

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <Button
                android:id="@+id/buttonRefresh"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="@string/esp_retrieve" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center"
                android:text="@string/esp_connection" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:gravity="fill_vertical"
                android:padding="10dp"
                android:text="@string/esp_ip" />

            <EditText
                android:id="@+id/editTextIP"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ems="10"
                android:inputType="date"
                android:padding="10dp" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/textView4"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:gravity="fill_vertical"
                android:padding="10dp"
                android:text="@string/esp_port" />

            <EditText
                android:id="@+id/editTextPort"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ems="10"
                android:inputType="number"
                android:padding="10dp" />

        </TableRow>

    </TableLayout>

</android.support.constraint.ConstraintLayout>

1 Ответ

0 голосов
/ 03 июня 2018

Решение 1

Используйте replace() вместо add() для добавления фрагмента в контейнер

Когда действие перезапускается из-за изменения ориентации, оно создаетсяеще один раз ConfigureFragment создается дважды.

Причина в том, что система автоматически восстанавливает активность и фрагмент, если приложение было убито системой.Сцена происходит в super.onCreate ().Поэтому приведенный выше код добавления фрагмента добавит дополнительный фрагмент поверх восстановленного фрагмента, что приведет к текущей ситуации.ScrollView не может иметь более одного дочернего элемента!

Решение 2

Если вы добавляете фрагмент в метод onCreate () своей деятельности, то проверьте переменную saveInstanceState (Bundle)объект).Это не ноль, когда активность воссоздана, тогда только добавьте свой фрагмент

if (savedInstanceState == null) {
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    ConfigureFragment fragment = new ConfigureFragment();
    fragment.setReferences(MainActivity.this, (Controller) spinner.getSelectedItem());
    fragmentTransaction.add(fragmentView.getId(), fragment, "");
    fragmentTransaction.commit();
}
...