Skip to content

Instantly share code, notes, and snippets.

@fdoyle
Last active June 14, 2018 08:42
Show Gist options
  • Save fdoyle/f89b9df46768ed6ca637 to your computer and use it in GitHub Desktop.
Save fdoyle/f89b9df46768ed6ca637 to your computer and use it in GitHub Desktop.
BaseAdapter that allows for delayed content
package com.lacronicus.delayedloadingadapterdriver.app;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import java.util.HashSet;
import java.util.Set;
/**
* this is an extension of baseadapter
* set this as your adapter AND set it as the scroll listener on your listview
* loadDelayableContent is called immediately following getInitialView while the listview is not being flung
* if the listview is in a "flinging" state, loadDelayableContent calls are delayed until the listview has come to a rest
*/
public abstract class DelayableBaseAdapter extends BaseAdapter implements ListView.OnScrollListener {
public static final int SCROLL_STATE_UNSET = -100;
int currentScrollState = SCROLL_STATE_UNSET;
Set<View> needContentLoadedSet;
protected DelayableBaseAdapter() {
needContentLoadedSet = new HashSet<View>();
}
@Override
public final View getView(int position, View convertView, ViewGroup parent) {
needContentLoadedSet.remove(convertView);
View v = getInitialView(position, convertView, parent);
//decide if loadDelayableContent should be called now or delayed
if (currentScrollState == SCROLL_STATE_TOUCH_SCROLL || currentScrollState == SCROLL_STATE_UNSET) {
loadDelayableContent(position, v);
if (needContentLoadedSet.contains(v)) {
needContentLoadedSet.remove(v);
}
} else {
needContentLoadedSet.add(v);
}
return v;
}
/*
* This is the equivalent of a standard getView
*
* */
public abstract View getInitialView(int position, View convertView, ViewGroup parent);
/*
* use this to make changes to your views once your listview is no longer scrolling
* */
public abstract void loadDelayableContent(int position, View view);
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
//use new scrollState and old scrollState to do our "state machine"
switch (scrollState) {
case SCROLL_STATE_FLING:
break;
case SCROLL_STATE_TOUCH_SCROLL:
case SCROLL_STATE_IDLE:
if (currentScrollState == SCROLL_STATE_FLING) { //don't call load content if no calls to loadUnloadedContent have been delayed
loadUnloadedContent(view);
}
break;
}
//update current state
currentScrollState = scrollState;
}
private void loadUnloadedContent(AbsListView lv) {
for (View v : needContentLoadedSet) {
loadDelayableContent(lv.getPositionForView(v), v);
}
needContentLoadedSet.clear();
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment