Android跨片段保留信息
我有五个片段供用户切换。其中一个片段从服务器加载一个用户列表,以填充片段上的UI列表。如果用户滑动到不同的片段,然后再滑动回原始片段,我需要保存列表信息。我不希望每次用户离开片段并返回时片段都重新加载用户 我正在查看SetRetainance(true),想知道这是否是可能的解决方案?片段保留信息而不必每次从头创建的最佳方式是什么Android跨片段保留信息,android,Android,我有五个片段供用户切换。其中一个片段从服务器加载一个用户列表,以填充片段上的UI列表。如果用户滑动到不同的片段,然后再滑动回原始片段,我需要保存列表信息。我不希望每次用户离开片段并返回时片段都重新加载用户 我正在查看SetRetainance(true),想知道这是否是可能的解决方案?片段保留信息而不必每次从头创建的最佳方式是什么 我使用它在片段之间切换-getSupportFragmentManager().beginTransaction().replace(R.id.searchLayou
我使用它在片段之间切换-getSupportFragmentManager().beginTransaction().replace(R.id.searchLayout,ratingFragment.commit() 通过将片段添加到backstack来替换片段
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.replace(container, fragment, tag);
fragmentTransaction.commit();
还要创建视图的对象,如果该对象不为null,则返回该对象
private void View view ;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (view != null)
return view;
view = inflater.inflate(R.layout.fragment_browse_recipe, container, false);
//initialize layout views
return view;
}
片段与任何其他对象一样。 在片段事务中,片段不调用OnCreate()方法,而是从onCreateView开始,因此,请加载用户并将其保存为实例变量,然后将其分配到OnCreate()中 范例
class MyFragment extends Fragment{
List<users> userList;
void onCreate(){
userList = getUserList();}
//the list is loaded during Oncreate();
这似乎是一个非常好的解决方案,也是迄今为止我见过的最简单的解决方案。谢谢你,我会试试这个,让你知道它是否有效!
void onCreateView(){
//you can check whether instance Variable is initialised or not
if(userList != null) {
listview.setAdapter(new Myadapter(this,userList);