多次调用 fragment 的 onCreateView

fragment's onCreateView called multiple times

所以我有一个设置片段,其 onCreateView 被多次调用。我有一个位于片段布局内部的 ViewPager,通过单击工具栏选项菜单中的设置图标启动片段。

而且我不能只将 ViewPager 移动到 activity,因为我希望能够滑动回到上一个片段。

此外,我尝试使用

删除后台堆栈中的片段
for(int i=0;i< Objects.requireNonNull(fm).getBackStackEntryCount();++i){
      fm.popBackStackImmediate();
   }

但这根本没有帮助。

片段代码:

public class SettingsFragment extends Fragment {
    
    public SettingsFragment() {
   
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }
    @Deprecated
    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        final View rootview = inflater.inflate(R.layout.fragment_settings, container, false);
        final CustomViewPager viewPager=rootview.findViewById(R.id.SettingsFragmentViewPager);
        viewPager.setAdapter(new Adapter(getFragmentManager()));
        viewPager.setOffscreenPageLimit(2);
        viewPager.setCurrentItem(1);
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    viewPager.setPagingEnabled(false);
                    FragmentManager fm=getFragmentManager();
                    for(int i=0;i< Objects.requireNonNull(fm).getBackStackEntryCount();++i){
                        fm.popBackStackImmediate();
                    }
                    viewPager.removeOnPageChangeListener(this);
                }
            }


        });
        return rootview;
       
    }

片段的xml:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:app="http://schemas.android.com/apk/res-auto"

                                                   xmlns:tools="http://schemas.android.com/tools"
                                                   xmlns:android="http://schemas.android.com/apk/res/android"
                                                   android:layout_height="match_parent"
                                                   android:layout_width="match_parent"
                                                   android:background="#fff" android:animationCache="true"
                                                   android:id="@+id/SettingsFragmentContainer"
                                                   android:clickable="true"
                                                   android:drawingCacheQuality="high" android:focusable="true">


        <androidx.appcompat.widget.Toolbar
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:background="?attr/colorPrimary"
                android:theme="?attr/actionBarTheme"
                android:minHeight="?attr/actionBarSize" app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                android:id="@+id/SettingsActivityToolbar" app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="1.0"/>
        <TextView
                android:text="Settings"
                android:layout_width="65dp"
                android:layout_height="23dp" app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toStartOf="parent" android:layout_marginTop="18dp"
                app:layout_constraintEnd_toEndOf="parent" android:id="@+id/Settings_textview"
                android:textAppearance="@style/ActionBar.nameText"/>
        <ImageButton
                android:layout_width="46dp"
                android:layout_height="34dp" app:srcCompat="@drawable/settings_icon_back"
                android:id="@+id/backPressButton"
                android:rotation="180" android:backgroundTint="#fff"
                android:background="@null"
                app:layout_constraintStart_toStartOf="@+id/SettingsActivityToolbar"
                android:layout_marginStart="2dp" app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="16dp" android:onClick="click" android:drawingCacheQuality="high"/>
        <TextView
                android:text=""
                android:layout_width="0dp"
                android:layout_height="0.1dp" app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent" android:id="@+id/linebreak1" android:layout_marginTop="10dp"
                app:layout_constraintTop_toBottomOf="@+id/backPressButton" android:background="#A1A8AC"/>
        <TextView
                android:layout_width="0dp"
                android:layout_height="0.1dp" android:id="@+id/linebreak2"
                android:background="#A1A8AC"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent" android:layout_marginTop="7dp"
                app:layout_constraintTop_toBottomOf="@+id/switch4"/>
        <Switch
                android:text="Test Test"
                android:layout_width="0dp"
                android:layout_height="47dp" android:id="@+id/switch4"
                android:textAppearance="@style/ActionBar.nameText" app:layout_constraintStart_toStartOf="parent"
                android:layout_marginStart="25dp" android:layout_marginEnd="25dp"
                app:layout_constraintEnd_toEndOf="parent" android:thumbTint="@drawable/switch_thumb_selector"
                android:trackTint="@drawable/switch_track_selector" android:layout_marginTop="18dp"
                app:layout_constraintTop_toBottomOf="@+id/backPressButton" tools:ignore="UseSwitchCompatOrMaterialXml"/>
        <TextView
                android:layout_width="0dp"
                android:layout_height="67dp" android:id="@+id/update"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                android:clickable="true"
                android:textAppearance="@style/ActionBar.nameText" app:layout_constraintHorizontal_bias="0.0"
                android:background="?attr/selectableItemBackground" android:layout_marginTop="16dp"
                app:layout_constraintTop_toBottomOf="@+id/switch4" android:onClick="onClickUpdate"
                android:focusable="true"/>
        <TextView
                android:text="test test"
                android:layout_width="wrap_content"
                android:clickable="true"
                android:layout_height="0dp" android:id="@+id/enter_version"
                app:layout_constraintTop_toTopOf="@+id/update"
                android:layout_marginTop="36dp" android:layout_marginEnd="206dp"
                app:layout_constraintEnd_toEndOf="@+id/update" android:focusable="true"/>
        <TextView
                android:text="Check Update"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:clickable="true"
                android:id="@+id/update_textview"
                android:textAppearance="@style/ActionBar.nameText" android:layout_marginEnd="228dp"
                app:layout_constraintEnd_toEndOf="@+id/update" app:layout_constraintTop_toTopOf="@+id/update"
                android:layout_marginTop="10dp" android:focusable="true"/>
        <com.testapp.test2.CustomViewPager
                android:layout_width="0dp"
                android:layout_height="0dp" app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent" app:layout_constraintVertical_bias="0.58000004"
                app:layout_constraintStart_toStartOf="parent" android:id="@+id/SettingsFragmentViewPager"
                />
</androidx.constraintlayout.widget.ConstraintLayout>

我为 ViewPager 使用的适配器:

public class Adapter extends FragmentStatePagerAdapter {

    public Adapter(FragmentManager fragmentManager){
        super(fragmentManager,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);

    }


    @NotNull
    @Override
    public Fragment getItem(int position) {
        if(position==0){
            return new BlankFragment();
        }

        if(position==1){
            return new SettingsFragment();
        }


        return null;
        }




    @Override
    public int getCount() {
        return 2;
    }


}

我看到在我的适配器中我也在 returning SettingsFragment。有没有办法 return 当我点击工具栏中的设置按钮时创建的片段?

顺便说一句,我使用这个添加片段:

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch(item.getItemId()){
            case R.id.updateId:
                Log.d("MAIN ACTIVITY---","ADDING FRAGMENT...");
                FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
                ft.setCustomAnimations(R.anim.push_right_in,0);
                ft.add(R.id.MainActivityConstraint,new SettingsFragment());
                ft.commit();
                Log.d("ACTIVITY---","Fragment added...");
                break;

               }
}

我决定使用名为 swipebacklayout 的外部库来代替 ViewPager。 你可以在这里查看。 https://github.com/gongwen/swipebacklayout