所以我有一个onCreate方法,它有一个片段事务,其片段名为selectedFragment,我在每个菜单案例中都会更改。我想保存该类片段当应用程序暂停以实例化相同的onResume / onRestart时,我将该片段名称保存在SharedPreferences的String中,方法为saveInfo:
@Override
protected void onPause() {
super.onPause();
saveInfo();
Toast.makeText(this, "Pause", Toast.LENGTH_SHORT).show();
}
protected void onResume(){
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences("selectedFragment", Context.MODE_PRIVATE);
String fragmentType = sharedPreferences.getString("fragmentType", "");
Toast.makeText(this, fragmentType, Toast.LENGTH_SHORT).show();
}
public void saveInfo(){
SharedPreferences sharedPreferences = getSharedPreferences("selectedFragment", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("fragmentType", selectedFragment.getClass().getSimpleName());
editor.apply();
}
所有信息都正确显示但我无法实例化片段,我尝试使用selectedFragment = Fragment.instantiate(getApplicationContext(), fragmentType)
和selectedFragment = Class.forName(fragmentType).newInstance();
并返回此异常未处理的异常:java.lang .ClassNotFoundException
PD:我从SharedPreferences获取的fragmentType字符串是正确的。
答案 0 :(得分:0)
如果你真的需要:
Fragment fragment = Class.forName("your.package.name.YourFragmentClassName").newInstance()