In Android applications such as Twitter (official app), when you encounter a ListView, you can pull it down (and it will bounce back when released) to refresh the content.
I wonder what is the best way, in your opinion, to implement that?
Some possibilities I could think of:
Any recommendations?
P.S. I wonder when the official Twitter app source code is released. It has been mentioned that it will be released, but 6 months has passed and we haven't heard about it since then.
Finally, Google released an official version of the pull-to-refresh library!
It is called SwipeRefreshLayout
, inside the support library, and the documentation is here:
Add SwipeRefreshLayout
as a parent of view which will be treated as a pull to refresh the layout. (I took ListView
as an example, it can be any View
like LinearLayout
, ScrollView
etc.)
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pullToRefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
Add a listener to your class
protected void onCreate(Bundle savedInstanceState) {
final SwipeRefreshLayout pullToRefresh = findViewById(R.id.pullToRefresh);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshData(); // your code
pullToRefresh.setRefreshing(false);
}
});
}
You can also call pullToRefresh.setRefreshing(true/false);
as per your requirement.
UPDATE
Android support libraries have been deprecated and have been replaced by AndroidX. The link to the new library can be found here.
Also, you need to add the following dependency to your project:
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
OR
You can go to Refactor>>Migrate to AndroidX and Android Studio will handle the dependencies for you.