Sanam Baig
Sanam Baig

Reputation: 109

How to give list view Pull Down to Refresh functionality in android

How can I create a pull down to refresh list in android?

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pull_to_refresh);

    // Set a listener to be invoked when the list should be refreshed.
    ((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
        @Override
        public void onRefresh() {
            // Do work to refresh the list here.
            new GetDataTask().execute();
        }
    });

    mListItems = new LinkedList<String>();
    mListItems.addAll(Arrays.asList(mStrings));

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, mListItems);

    setListAdapter(adapter);
}`

Upvotes: 3

Views: 1964

Answers (1)

Robin Eisenberg
Robin Eisenberg

Reputation: 1866

This is not an android design pattern. However, this excellent library lets you do it easily. Have a look at the examples.

Hope I helped.

Edit -- 12/06/2015 -- Disregard the previous statement:

This is now a design pattern that is fully supported by the SDK on Android.

It is very simple, you need to use a SwipeRefreshLayout as the parent view to your list (or other data you might want to refresh). You can put any view as a child, it will create a Pull-To-Refresh animation for that view.

Aftewards, you just need to implement SwipeRefreshLayout.OnRefreshListener to handle the network code of the actual data refresh:

public class MainActivity extends FragmentActivity implements OnRefreshListener {

private SwipeRefreshLayout _pullToRefreshLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_main);

    _pullToRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout);
    _pullToRefreshLayout.setOnRefreshListener(this);

    super.onCreate(savedInstanceState);
}

@Override
public void onRefresh() {
    //When this is called, your view has a little loader showing to show the user that a network call is in progress
    Log.i("SO17065814", "Starting refresh...");

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            mSwipeRefreshLayout.setRefreshing(false); //This stops the refresh animation
            Log.i("SO17065814", "Ending refresh...");
        }
    }, 5000);
}

}

Upvotes: 3

Related Questions