As the name says, SwipeRefreshLayout lets the users to reload the contents of the page just by swiping the screen down. If you have used Google Chrome or Gmail in your smart phones, you might have seen/used this feature. It is fairly easy to implement this widget.
Here is a live demo of the expected output.
This is the import code used to import SwipeToRefresh feature into our Layout:
import android.support.v4.widget.SwipeRefreshLayout;
In the layout xml page, use this code to implement SwipeToRefresh layout:
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/swiperefresh" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="5dp"> </android.support.v4.widget.SwipeRefreshLayout>
Here is a Sample code to understand how to implement SwipeToRefresh layout in a real-time project.
In this project, we will be using a ListView to show to data in the page.
<ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="match_parent" />
First, let us create a String Array of County names to be displayed in the ListView.
On a newly created project, create a java class named Data and create an Array List to store the County names.
Data java class
import java.util.ArrayList; import java.util.HashSet; import java.util.Random; public class Data { static final String[] county = { "Los Angeles", "Cook", "Harris", "Maricopa", "San Diego", "Orange", "Miami-Dade", "Kings", "Dallas", "Queens", "Riverside", "San Bernardino", "King", "Clark", "Tarrant", "Santa Clara", "Broward", "Bexar", "Wayne", "New York", "Philadelphia", "Alameda", "Middlesex", "Suffolk", "Sacramento", "Bronx", "Nassau", "Palm Beach", "Cuyahoga", "Hillsborough", "Allegheny", "Oakland", "Franklin", "Orange", "Hennepin", "Fairfax", "Contra Costa", "Travis", "Salt Lake", "St. Louis", "Montgomery", "Pima", "Honolulu", "Westchester", "Milwaukee", "Fulton", "Mecklenburg", "Fresno", "Shelby", "Wake", "Fairfield", "DuPage", "Erie", "Pinellas", "Marion", "Bergen", "Hartford", "Prince George's", "Duval", "New Haven", "Kern", "Macomb", "Ventura", "Gwinnett", "El Paso", "San Francisco", "Collin", "Baltimore", "Pierce", "Montgomery", "Worcester", "Hamilton", "Hidalgo", "Essex", "Multnomah", "Jefferson", "Monroe", "Oklahoma", "Suffolk", "San Mateo", "Snohomish", "Lake", "DeKalb", "Cobb", "San Joaquin", "Denton", "Will", "Jackson", "Norfolk", "Bernalillo", "Jefferson", "Hudson", "El Paso", "Davidson", "Lee", "Monmouth", "Bucks", "Providence" }; //method to generate an ArrayList of random contents from string array county public static ArrayListrandomList(int count) { Random random = new Random(); HashSet item = new HashSet (); count = Math.min(count, county.length); while (item.size() < count) { item.add(county[random.nextInt(county.length)]); } return new ArrayList (item); } }
Next, Create a new FragmentActivity (java > "your_package_name" > (right_click)New > Fragment > Fragment(Blank) and name it as SwipeRefreshFragment.
SwipeRefreshFragment java class:
import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.List; public class SwipeRefreshFragment extends Fragment { private static final int Item_Count = 15; SwipeRefreshLayout refreshLayout; private ListView countyList; private ArrayAdapterlistAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //inflate view of this Fragment View view = inflater.inflate(R.layout.fragment_swipe_refresh, container, false); //initialize SwipeRefreshLayout refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swiperefresh); //set colors for loading progressbar refreshLayout.setColorSchemeColors(0xFFFF0000, 0xFF00FF00); //initialize ListView countyList = (ListView) view.findViewById(android.R.id.list); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); //initialize adapter to show lstitems listAdapter = new ArrayAdapter ( getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, Data.randomList(Item_Count)); //set adapter to ListView countyList.setAdapter(listAdapter); //OnRefreshListener executes when layout is pull down to perform a refresh refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { startRefresh(); } }); } //method to add content to listview while refresh private void startRefresh() { new BackgroundTask().execute(); } //this method executes after loading contents private void onRefreshComplete(List result) { //clear the existing adapter listAdapter.clear(); //add new list to adapter for (String county : result) { listAdapter.add(county); } refreshLayout.setRefreshing(false); } //Async task to load data //here a timer is implemented in doInBackground private class BackgroundTask extends AsyncTask > { //duration of the swipe feature static final int Duration = 3000; @Override protected List doInBackground(Void... params) { try { Thread.sleep(Duration); } catch (InterruptedException e) { e.printStackTrace(); } return Data.randomList(Item_Count); } @Override protected void onPostExecute(List result) { super.onPostExecute(result); //after finishing doInbackground OnRefreshComplete is called onRefreshComplete(result); } } }
In the fragment_swipe_refresh.xml, inside a SwipeRefreshLayout, copy this code:
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/swiperefresh" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="5dp"> <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="match_parent" /> </android.support.v4.widget.SwipeRefreshLayout>
In the activity_main.xml, place a FrameLayout to place the fragment. The ListView will now be displayed inside this FrameLayout.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/sample_main_layout"> <FrameLayout android:id="@+id/fragment_content" android:layout_weight="1" android:layout_width="match_parent" android:layout_height="0px" /> </LinearLayout>
Now in the MainActivity java class, initialize the SwipeRefreshFragment :
MainActivity java class
import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { SwipeRefreshFragment fragment = new SwipeRefreshFragment(); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); //Add fragment to FrameLayout in activity_main transaction.replace(R.id.fragment_content, fragment); transaction.commit(); } } }
With this the setup is complete. Now try running the app & you should get the output, you see in the live demo.