A common feature that most apps will need is a way to get new content and a way to get old content. To achieve this goal with need to implement the SwipeRefreshLayout, a standard PullToRefresh provided by Android SDK. The SwipeRefreshLayout can only hold one child, a scrollable view, in that case we will use a listview.

I will also explain how to get new items when the list reaches the bottom.

SwipeRefreshLayout

<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipe_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>
</android.support.v4.widget.SwipeRefreshLayout>
...
mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);

mSwipeLayout.setColorSchemeColors(Color.parseColor("#ff0000"),
 Color.parseColor("#00ff00"),Color.parseColor("#0000ff"),
 Color.parseColor("#f234ab"));
mSwipeLayout.setOnRefreshListener(new OnRefreshListener() {

	@Override
	public void onRefresh() {
		//Handle the refresh then call
		mSwipeLayout.setRefreshing(false);

	}
});
...

The only customizable we can do is change the four colors used in the animation.

AutoLoad

In order to make listview get new content when it reaches the bottom, or when it gets close we only need to set a scroll listener and verify when bottom is reached.

final int endTrigger = 2; // load more content 2 items before the end
mListView.setOnScrollListener(new OnScrollListener() {

	@Override
	public void onScrollStateChanged(AbsListView arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,int totalItemCount) {
		if (mListView.getCount() != 0
				&& mListView.getLastVisiblePosition() >= (mListView.getCount() - 1) - endTrigger) {
			// Do what you need to get more content.
			loadMore();
		}

	}
});

You can also create a custom Listview to this purpose and add your convenient methods, add a footer with loading feedbacks, etc…

Frederico Silva

Software Engineer

fredericojssilva fredericojss


Published