Maintain/Save/Restore scroll position when returning to a ListView

后端 未结 20 1646
無奈伤痛
無奈伤痛 2020-11-21 21:30

I have a long ListView that the user can scroll around before returning to the previous screen. When the user opens this ListView again, I want the

20条回答
  •  北海茫月
    2020-11-21 22:19

    If you're using fragments hosted on an activity you can do something like this:

    public abstract class BaseFragment extends Fragment {
         private boolean mSaveView = false;
         private SoftReference mViewReference;
    
         @Override
         public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
              if (mSaveView) {
                   if (mViewReference != null) {
                        final View savedView = mViewReference.get();
                        if (savedView != null) {
                             if (savedView.getParent() != null) {
                                  ((ViewGroup) savedView.getParent()).removeView(savedView);
                                  return savedView;
                             }
                        }
                   }
              }
    
              final View view = inflater.inflate(getFragmentResource(), container, false);
              mViewReference = new SoftReference(view);
              return view;
         }
    
         protected void setSaveView(boolean value) {
               mSaveView = value;
         }
    }
    
    public class MyFragment extends BaseFragment {
         @Override
         public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
              setSaveView(true);
              final View view = super.onCreateView(inflater, container, savedInstanceState);
              ListView placesList = (ListView) view.findViewById(R.id.places_list);
              if (placesList.getAdapter() == null) {
                   placesList.setAdapter(createAdapter());
              }
         }
    }
    

提交回复
热议问题