如何解决容器,碎片旋转
我有一个活动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 举报,一经查实,本站将立刻删除。