我有一个带有recyclerview的活动。在recyclerview的适配器中,当用户单击元素时,会创建一个新的片段。问题是,当我按下主页按钮,杀死应用程序进程然后恢复应用程序时,不会重新创建该分段。如何在应用程序进程被杀后恢复片段?
编辑:
活动中的onCreate方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
rvMain = (RecyclerView) findViewById(R.id.rvMain);
rvMain.setLayoutManager(new LinearLayoutManager(context));
MainAdapter adapter = new MainAdapter(numbers, context);
rvMain.setAdapter(adapter);
}
在recyclelerview适配器中的onBindViewHolder方法,其中调用了fragment:
@Override
public void onBindViewHolder(MainViewHolder holder, final int position) {
final Number number = numbers.get(position);
holder.lytMain.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DetailedFragment fragment = new DetailedFragment();
Bundle bundle = new Bundle();
bundle.putString("message", number.getName());
fragment.setArguments(bundle);
((MainActivity) context).getSupportFragmentManager().beginTransaction()
.addToBackStack("fragment")
.replace(R.id.lytDetailed, fragment)
.commit();
}
});
}
答案 0 :(得分:0)
我找到了一个解决方案,我将一个片段调用到MainActivity中的一个方法,然后用onSaveInstanceState保存片段实例并用onRestoreInstanceState恢复它。这是它的外观。
适配器中的onBindViewHolder:
@Override
public void onBindViewHolder(MainViewHolder holder, final int position) {
final Number number = numbers.get(position);
holder.lytMain.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((MainActivity)context).getFragment(number);
}
});
}
MainActivity中的getFragment()方法:
public void getFragment(Number number){
fragment = new DetailedFragment();
Bundle bundle = new Bundle();
bundle.putString("message", number.getName());
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction()
.addToBackStack("fragment")
.replace(R.id.lytDetailed, fragment)
.commit();
}
onSaveInstanceState和onRestoreInstanceState:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "detailed_fragment", fragment);
}
@Override
protected void onRestoreInstanceState(Bundle outState) {
super.onRestoreInstanceState(outState);
fragment = (DetailedFragment) getSupportFragmentManager()
.getFragment(outState, "detailed_fragment");
getSupportFragmentManager().beginTransaction()
.addToBackStack("fragment")
.replace(R.id.lytDetailed, fragment)
.commit();
}