jpelgrim
4/7/2014 - 10:23 AM

FrozenListFragment

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.AbsListView;

public class FrozenListFragment extends ListFragment {

    private static final String ARG_Y = "y";

    private static final String ARG_POSITION = "position";

    private int position = -1;

    private int y = 0;

    private Handler mHandler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        restoreStateFromBundle(savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_IDLE) {
                    storeListPosition(view);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }

        });
    }

    @Override
    public void onViewStateRestored(Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        restoreStateFromBundle(savedInstanceState);
    }

    private void restoreStateFromBundle(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            position = savedInstanceState.getInt(ARG_POSITION);
            y = savedInstanceState.getInt(ARG_Y);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(ARG_POSITION, position);
        outState.putInt(ARG_Y, y);
    }

    @Override
    public void onResume() {
        super.onResume();
        restoreListPosition();
    }

    private void storeListPosition(AbsListView listView) {
        position = listView.getFirstVisiblePosition();
        View v = listView.getChildAt(0);
        y = (v == null) ? 0 : v.getTop();
    }

    public void restoreListPosition() {
        if (position >= 0) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (getView() != null) {
                        getListView().setSelectionFromTop(position, y);
                    }
                }
            });
        }
    }

}