Sunday, 7 December 2014

SwipeRefreshLayout example


SwipeRefreshLayout example

      The SwipeRefreshLayout should be used whenever the user can refresh the contents of a view via a vertical swipe gesture. The activity that instantiates this view should add an OnRefreshListener to be notified whenever the swipe to refresh gesture is completed. 

       The SwipeRefreshLayout will notify the listener each and every time the gesture is completed again; the listener is responsible for correctly determining when to actually initiate a refresh of its content. If the listener determines there should not be a refresh, it must call setRefreshing(false) to cancel any visual indication of a refresh. 

        
        If an activity wishes to show just the progress animation, it should call setRefreshing(true). To disable the gesture and progress animation, call setEnabled(false) on the view.


First,


Add the SwipeRefreshLayout view into the layout .



<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/SwipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</android.support.v4.widget.SwipeRefreshLayout> 



Then,

initialize the SwipeRefreshLaout and listview and set the adapter to the listview.


swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.SwipeRefreshLayout);
  swipeRefreshLayout.setColorScheme(android.R.color.holo_blue_light);
  swipeRefreshLayout.setOnRefreshListener(refreshListener);
  listView = (ListView)findViewById(R.id.listView1);
  adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, items);
  listView.setAdapter(adapter);



implement the OnRefreshListener and refresh the listview,



private OnRefreshListener refreshListener = new OnRefreshListener() {
  
  @Override
  public void onRefresh() {
   // TODO Auto-generated method stub
   handler.post(refreshers);
  }
 };
 
 private Runnable refreshers = new Runnable() {
  
  @Override
  public void run() {
   // TODO Auto-generated method stub
   swipeRefreshLayout.setRefreshing(true);
   handler.removeCallbacks(refreshers);
   i = i+1;
   items.add(""+i);
   new Handler().postDelayed(new Runnable() {
    
    @Override
    public void run() {
     // TODO Auto-generated method stub
     swipeRefreshLayout.setRefreshing(false);   
    }
   },2000);
   adapter.notifyDataSetChanged();
  handler.postDelayed(refreshers, 8000);
   
  }
 };


Screenshot :

DOWNLOAD SAMPLE CODE

No comments: