Почему этот код не дает исключение нулевого указателя? - PullRequest
0 голосов
/ 12 октября 2019

Я немного запутался в приведенном ниже коде, где я добавляю Fragment в метод Fragment, onCreateView() перед добавлением его View. С моей точки зрения, поскольку я еще не установил View, поэтому, когда R.id.rv_container вызовет, чтобы получить FrameLayout для этого Child Fragment, он получит исключение null указателя, но этого не происходит. Это работает хорошо. Так в чем же причина этого? Почему я ошибаюсь в null исключении указателя?

Класс фрагмента:

public class Chats extends Fragment {

    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater,
            ViewGroup container,
            Bundle savedInstanceState
    ) {
        initRvView();
        return inflater.inflate(R.layout.fragment_chat,
                container, false);
    }

    private void initRvView() {
        final String POST_RV = "chat_recycler";
        RecyclerViewFragment recyclerViewFragment = (RecyclerViewFragment)
                getChildFragmentManager()
                        .findFragmentByTag(POST_RV);
        if (recyclerViewFragment == null) {
            recyclerViewFragment = new RecyclerViewFragment(FROM_MESSAGING);
        }
        getChildFragmentManager().beginTransaction()
                .replace(R.id.rv_container,
                        recyclerViewFragment,
                        POST_RV)
                .commit();
    }
}

Макет фрагмента (R.layout.fragment_chat):

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <FrameLayout
            android:id="@+id/rv_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Если вы посмотрите на код, initRvView() метод вызывает перед установкой View, но не показывает никаких исключений указателя null.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...