Tuesday, December 16, 2014

Android Pull to Refresh Layout

The SwipeRefreshLayout should be used whenever the user can refresh the contents of 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. 

Methods:
 setOnRefreshListener(OnRefreshListener): adds a listener to let other parts of the code know when refreshing begins.

 setRefreshing(boolean): enables or disables progress visibility.


 isRefreshing(): checks whether the view is refreshing.


 setColorScheme(): it receive four different colors that will be used to colorize the animation.



We begin implementing the Swipe to Refresh pattern with a brand new Android Studio project and the most recent version of the Android Support Library (your SDK manager should show an Android Support Library version of at least 21.0).
compile 'com.android.support:support-v4:21.0.+'
<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/swipe_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:text="@string/hello_world"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:gravity="center"/>
    </ScrollView>
 </android.support.v4.widget.SwipeRefreshLayout>

We just need to get the layout, and assign some colours and the listener. The refreshing listener is a post delayed handler.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
    swipeLayout.setOnRefreshListener(this);
    swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
            android.R.color.holo_green_light,
            android.R.color.holo_orange_light,
            android.R.color.holo_red_light);
}


@Override public void onRefresh() {
    new Handler().postDelayed(new Runnable() {
        @Override public void run() {
            swipeLayout.setRefreshing(false);
        }
    }, 5000);
}

No comments:

Post a Comment