简体   繁体   English

何时/如何添加 ListView Adapter,它会通过后退按钮恢复? (分段)

[英]When/How to add ListView Adapter, that it gets restored with back button? (Fragment)

When / How to add a ListView Adapter, that it gets restored with back button?何时/如何添加一个 ListView 适配器,它可以通过后退按钮恢复? I want to move back from FragmentB to Fragment A and have the same Adapter as I had before going to FragmentB .我想从FragmentB移回Fragment A并拥有与转到FragmentB之前相同的 Adapter 。

@Override
public void onViewCreated(@NonNull View view, @Nullable final Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    adapter = new UserAdapter(getContext(), R.layout.list_item, userList);
}

With this I am always creating a new one.有了这个,我总是在创造一个新的。 I just want to create it once and then keep it.我只想创建一次然后保留它。

I found a solution .我找到了解决办法 For anyone that has the same question:对于任何有同样问题的人:

Create a boolean inside your Fragment like this and check in which version your Fragment is.像这样在您的 Fragment 中创建一个布尔值,并检查您的 Fragment 是哪个版本。 Like this you can only initially create your adapter at the beginning and not override it every time you come back.像这样,您只能在开始时最初创建适配器,而不能在每次回来时覆盖它。

public class MyFragment extends Fragment {
    private boolean isCreated;
    private MyAdapter adapter;

    public MyFragment() {
    // Required empty public constructor
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable final Bundle savedInstanceState) {
       super.onViewCreated(view, savedInstanceState);
       if(!isCreated){
          adapter = new MyAdapter(getContext(), R.layout.list_item, myList);
       }
       // create your listView here, set adapter and set onItemClickListener..
    }

    @Override
    public void onResume() {
       super.onResume();
       if(!isCreated)
       {
          isCreated = true;
       }
}

The actual solution depends on your fragment transactions and the fact if your Fragment gets destroyed during the transaction or not.实际的解决方案取决于您的 Fragment 交易以及您的 Fragment 是否在交易期间被销毁的事实。

If it survives after returning from the second fragment, then you can simply use an other lifecycle callback (onCreated).如果它在从第二个片段返回后仍然存在,那么您可以简单地使用其他生命周期回调 (onCreated)。 This way your adapter will be created only once:这样您的适配器将只创建一次:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    adapter = new MyAdapter( ... );
}

If your fragment does not survive (if it gets replaced and destroyed), then you have to save the state of your adapter, create a new one and apply the old (saved) state to it.如果您的片段不存在(如果它被替换和销毁),那么您必须保存适配器的状态,创建一个新的并将旧的(保存的)状态应用于它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM