Android Fragment

Я попытался из Activity перенести код в Fragment и вроде бы ошибок нет но при попытке открыть приложение он крашится. Проверьте пожалуйся что не так

Xml файл

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <Button
                android:id="@+id/btn1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="expand relativelayout" />


            <com.example.admin1.bottomtabexample.Locations.ExpandableRelativeLayout
                android:id="@+id/collapseView1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:duration="50"
                app:expandable="true">

                <LinearLayout
                    android:id="@+id/ll_1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <Button
                        android:layout_width="125dp"
                        android:layout_height="125dp" />
                </LinearLayout>
            </com.example.admin1.bottomtabexample.Locations.ExpandableRelativeLayout>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <Button
                android:id="@+id/btn2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="expand relativelayout" />

            <com.example.admin1.bottomtabexample.Locations.ExpandableRelativeLayout
                android:id="@+id/collapseView2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:duration="50"
                app:expandable="true">

                <LinearLayout
                    android:id="@+id/ll_2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <Button
                        android:layout_width="125dp"
                        android:layout_height="125dp"
                        android:text="awdwawad" />
                </LinearLayout>
            </com.example.admin1.bottomtabexample.Locations.ExpandableRelativeLayout>
        </LinearLayout>
    </LinearLayout>
</ScrollView>

Java файл

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

import androidx.fragment.app.Fragment;

import com.example.admin1.bottomtabexample.Locations.ExpandableRelativeLayout;
import com.example.admin1.bottomtabexample.R;


public class ItemFiveFragment extends Fragment implements View.OnClickListener {

    private ExpandableRelativeLayout mCollapseView1;
    private ExpandableRelativeLayout mCollapseView2;

    public static ItemFiveFragment newInstance() {
        return new ItemFiveFragment();
    }

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }
    private void init()
    {
        Button btn1 = requireView().findViewById(R.id.btn1);
        btn1.setOnClickListener(this);
        mCollapseView1 = requireView().findViewById(R.id.collapseView1);
        LinearLayout ll_1 = requireView().findViewById(R.id.ll_1);
        ll_1.setOnClickListener(this);

        Button btn2 = requireView().findViewById(R.id.btn2);
        btn2.setOnClickListener(this);
        mCollapseView2 = requireView().findViewById(R.id.collapseView2);
        LinearLayout ll_2 = requireView().findViewById(R.id.ll_2);
        ll_2.setOnClickListener(this);

    }
    public void onClick(View v) {
        if (v.getId() == R.id.btn1) {
            mCollapseView1.toggle();
        }
        if (v.getId() == R.id.btn2) {
            mCollapseView2.toggle();
        }
    }
}

Это что выдало в логах введите сюда описание изображения


Ответы (1 шт):

Автор решения: Damir Fazullin

Жизненный цикл fragment.

1. Сперва вызывается onCreate() - это говорит о том, что ваш Fragment был создан.

2. Затем вызывается onCreateView - в этом методе в фрагмент раздувается layout.

3. После onViewCreated - в этом методе Fragment сообщает, что он успешно раздул layout и теперь View часть готова к работе.

Проблема:

Вы inflate-итите layout в методе onCreateView и в методе onCreate обращаешься к view компонентам методом findViewById. В момент когда обращения к view элементам в методе onCreate метод onCreateView еще не был вызван и соответсвенно view компоненты у фрагмента еще не существуют.

Решение:

Инициализировать элементы необходимо в методе onCreateView() вызывая метод findViewById на корневой View:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    View root =  inflater.inflate(R.layout.fragment_item_setting, container, false);
    root.findViewById(R.id.yourView);
    return root;
 }

По факту ваш метод init() должен быть этом методе.

→ Ссылка