FragmentStatePagerAdapter не может сохранить состояние - PullRequest
0 голосов
/ 24 октября 2019

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

Приложение должно дать вам шесть вопросов, а выдолжен быть в состоянии провести пальцем влево и вправо для навигации между вопросами. Этот функционал работает. Это выглядит так:

enter image description here

Эти вопросы и ответы создаются динамически из БД с использованием Android Room. Я генерирую 6 уникальных вопросов, и каждый вопрос добавляет Фрагмент в FragmentStatePagerAdapter. Проблема возникает, когда вы на самом деле пролистывать вопросы. Как только вы дойдете до вопроса 3 и вернетесь к вопросу 1, вопрос 1 будет выглядеть следующим образом:

enter image description here

Я понимаю, что Фрагмент уничтожается изатем восстановлен. Однако, используя Log.d, я обнаружил, что onCreate по-прежнему вызывает точно так же и даже снова получает все ответы. Проблема в том, что он не назначает его переключателям, и я не знаю почему. OnCreate для фрагмента выглядит следующим образом:

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.page_1, container, false);

    states = rootView.findViewById(R.id.textView5);
    radioGroup = rootView.findViewById(R.id.radioGroup);
    questionCount = rootView.findViewById(R.id.questionCount);

    answerRadios.add(rootView.findViewById(R.id.radioButton));
    answerRadios.add(rootView.findViewById(R.id.radioButton2));
    answerRadios.add(rootView.findViewById(R.id.radioButton3));

    questionCount.setText("Question " + order + "/6");

    // Gets the question in this particular order
    LiveDataUtil.observeOnce(db.questions().getQuestion(qId, order), (question) -> {
        states.setText("What is the capital of " + question.state + "?");

        // Get the answers for the question
        LiveDataUtil.observeOnce(db.answers().getAnswers(question.id), (answers) -> {
            for (int i = 0, len = answers.size(); i < len; i++) {
                RadioButton radio = answerRadios.get(i);
                QuizAnswer answer = answers.get(i);

                radio.setText(answer.answerText);
            }
        });

         radioGroup.setOnCheckedChangeListener
          ...more code
    });

    return rootView;
}

Шаблон фрагмента (page_1.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="30dp"
        android:text="Capital Quiz!"
        android:textSize="36sp" />

    <TextView
        android:id="@+id/questionCount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="30dp"
        android:text="Question 1/6" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="QUESTION"
        android:textSize="18sp" />

    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="30dp">

        <RadioButton
            android:id="@+id/radioButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:text="Answer 1" />

        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:text="Answer 2" />

        <RadioButton
            android:id="@+id/radioButton3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Answer 3" />
    </RadioGroup>
</LinearLayout>

Для справки, LiveDataUtil выглядит так:

public class LiveDataUtil {
    public static <T> void observeOnce(LiveData<T> liveData, Observer<T> observer) {
        liveData.observeForever(o -> {
            liveData.removeObserver(observer);
            observer.onChanged(o);
        });
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...