容器,碎片旋转

问题描述

我有一个活动ContainerOfReports,其中包含对两个片段的引用。旋转手机时,出现以下异常-

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.salary/com.example.salary.MainScreens.Fragments.ContainerOfReports}: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.salary.MainScreens.Fragments.MonthsFragment: Could not find Fragment constructor

因此,为了解决此问题,我决定初始化savedInstanceState = null。它解决了问题,但是我认为这不是一个好的解决方案。也许有人对这种问题有更好的解决方案。谢谢。


public class ContainerOfReports extends AppCompatActivity {

    private static final String TAG = "MonthsFragmentContainer";
    private Context context;
    private BottomNavigationView botNav;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        savedInstanceState = null;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_monthly_container);

        initializeObjects();
        initializeSupportFragment(new MonthsFragment(context));
    }

    private void initializeObjects() {
        context = this;
        botNav = findViewById(R.id.detailsBotNav);
        botNav.setVisibility(View.VISIBLE);
        botNav.setonNavigationItemSelectedListener(navListener);
    }

    private void initializeSupportFragment(Fragment nextFragment) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment_container,nextFragment)
                .commit();
    }

    //Checking which fragment to display to user
    private BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            initializeSupportFragment(checkWhichFragmentSelected(item));
            return true;
        }
    };



    private Fragment checkWhichFragmentSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.fragReport:
                return new DetailReportFragment(context);
            default:
                return new MonthsFragment(context);
        }
    }

    @Override
    public void onBackpressed() {
        super.onBackpressed();
        finish();
    }


}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)