简体   繁体   中英

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? I want to move back from FragmentB to Fragment A and have the same Adapter as I had before going to FragmentB .

@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. 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.

If it survives after returning from the second fragment, then you can simply use an other lifecycle callback (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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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