Android SwipeRefreshLayout is a ViewGroup that can hold only one scrollable child. It can be either a ScrollView, ListView or RecyclerView. The basic need for a SwipeRefreshLayout is to allow the users to refresh the screen manually.
<android.support.v4.widget.SwipeRefreshLayoutFirst we create a simple swipe refresh layout as the viewgroup which will be holding the ListView like below. I have named it as swipe_refresh_layout.xml
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.widget.SwipeRefreshLayout>
<?xml version="1.0" encoding="utf-8"?>Once the layout is created, time to look at our Activity. I have created a sample SwipeRefreshLayoutClass.java. This will act as our Activity.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipeToRefresh"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</ListView>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
public class SwipeRefreshLayoutClass extends AppCompatActivity {
ArrayList arrayList = new ArrayList();
SwipeRefreshLayout mSwipeRefreshLayout;
ListView mListView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.swipe_refresh_layout);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeToRefresh);
mListView = (ListView) findViewById(R.id.listView);
mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
mListView.setAdapter(adapter);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
int rand = new Random().nextInt(500)+1;
arrayList.add(String.valueOf(rand));
adapter.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
}
});
}
}