[Android Notes] RecyclerView + SwipeRefreshLayout example, swiperefreshlayout

Source: Internet
Author: User

[Android Notes] RecyclerView + SwipeRefreshLayout example, swiperefreshlayout
In this article, you will learn: 1. Basic usage of RecyclerView; 2. Basic usage of SwipeRefreshLayout; 3. Add response events for items in RecyclerView.
RecyclerView is used to replace the traditional ListView. RecyclerView is more flexible and can be used with animations. You can easily add various animation effects for each item. In addition, recyclerView enforces ViewHolder mode to improve performance.

:


Step: 1. Add dependency:

 compile 'com.android.support:recyclerview-v7:21.0.0' compile 'com.android.support:support-v4:22.0.0'
2. Compile the activity layout:
<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"                tools:context="com.taobao.recyclerviewwithrefresh.ui.activity.GridActivity">    <android.support.v4.widget.SwipeRefreshLayout        android:id="@+id/refreshLayout_grid"        android:layout_width="match_parent"        android:layout_height="match_parent">        <android.support.v7.widget.RecyclerView            android:id="@+id/recyclerView_grid"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:scrollbars="vertical"            ></android.support.v7.widget.RecyclerView>    </android.support.v4.widget.SwipeRefreshLayout></RelativeLayout>
3. Compile the layout of each item:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:orientation="horizontal"              android:layout_width="match_parent"              xmlns:tools="http://schemas.android.com/tools"              android:layout_height="50dp">    <ImageView        android:src="@mipmap/ic_launcher"        android:padding="5dp"        android:layout_width="wrap_content"        android:layout_height="wrap_content"/>    <TextView        android:id="@+id/tv"        android:layout_width="wrap_content"        android:textSize="18sp"        android:gravity="center"        android:layout_height="match_parent"        tools:text="ss"/></LinearLayout>
4. Data source:
Package com. taobao. recyclerviewwithrefresh. data; import java. util. arrayList; import java. util. list;/*** Created by Rowandjj on 2015/3/24. */public class DataSource {public static final List <String> generateData (int size) {if (size <= 0) return null; list <String> datas = new ArrayList <> (); for (int I = 0; I <size; I ++) {datas. add ("This Is List Data" + I);} return datas ;}}
5. separators:
Package com. taobao. recyclerviewwithrefresh. ui. adapter; import android. content. context; import android. content. res. typedArray; import android. graphics. canvas; import android. graphics. drawable. drawable; import android. support. v7.widget. recyclerView; import android. view. view;/*** Created by Rowandjj on 2015/3/24. */public class MyItemDecoration extends RecyclerView. itemDecoration {private static final int [] ATTRS = {android. r. attr. listDivider}; private Drawable mDivider; public MyItemDecoration (Context context) {TypedArray array = context. obtainStyledAttributes (ATTRS); // gets the separator entry mDivider = array. getDrawable (0); array. recycle () ;}@ Override public void onDrawOver (Canvas c, RecyclerView parent, RecyclerView. state state) {super. onDrawOver (c, parent, state); int count = parent. getChildCount (); int left = parent. getPaddingLeft (); int right = parent. getWidth ()-parent. getPaddingRight (); for (int I = 0; I <count; I ++) {View v = parent. getChildAt (I); RecyclerView. layoutParams params = (RecyclerView. layoutParams) v. getLayoutParams (); int top = v. getBottom () + params. bottomMargin; int bottom = top + mDivider. getIntrinsicHeight (); mDivider. setBounds (left, top, right, bottom); mDivider. draw (c );}}}
6. Write a data adapter and add a click RESPONSE event to it.
Package com. taobao. recyclerviewwithrefresh. ui. adapter; import android. support. v7.widget. recyclerView; import android. view. layoutInflater; import android. view. view; import android. view. viewGroup; import android. widget. textView; import com. taobao. recyclerviewwithrefresh. r; import java. util. list;/*** Created by Rowandjj on 2015/3/24. **/public class MainRecyclerAdapter extends RecyclerView. adapter <MainRecy ClerAdapter. viewHolder> {private List <String> datas = null; private OnItemClickListener mListener; public void setOnItemClickListener (OnItemClickListener listener) {this. mListener = listener;} public MainRecyclerAdapter (List <String> datas) {this. datas = datas ;}@ Override public ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {final View itemView = LayoutInflater. from (parent. getC Ontext ()). inflate (R. layout. item, parent, false); itemView. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {if (mListener! = Null) {mListener. onItemClick (v, (String) itemView. getTag () ;}}); return new ViewHolder (itemView) ;}@ Override public void onBindViewHolder (ViewHolder holder, int position) {String s = datas. get (position); holder. bindData (s); holder. itemView. setTag (s) ;}@ Override public int getItemCount () {return datas. size ();}/*** batch add **/public void addItems (List <String> items) {if (items = null) Return; this. datas. addAll (0, items); this. policyitemrangeinserted (0, items. size ();} public interface OnItemClickListener {public void OnItemClick (View view, String data);} static class ViewHolder extends RecyclerView. viewHolder {private TextView mContent; public ViewHolder (View itemView) {super (itemView); mContent = (TextView) itemView. findViewById (R. id. TV);} public void bindData (String s ){ If (s! = Null) mContent. setText (s );}}}

RecyclerView does not provide callbacks such as onItemClickListener. Here we implement one by ourselves...

7. Home Page code:
Package com. taobao. recyclerviewwithrefresh. ui. activity; import android. content. intent; import android. OS. asyncTask; import android. OS. bundle; import android. support. v4.widget. swipeRefreshLayout; import android. support. v7.app. actionBarActivity; import android. support. v7.widget. linearLayoutManager; import android. support. v7.widget. recyclerView; import android. view. menu; import android. view. menuItem; import android. view. view; import android. widget. toast; import com. taobao. recyclerviewwithrefresh. r; import com. taobao. recyclerviewwithrefresh. data. dataSource; import com. taobao. recyclerviewwithrefresh. ui. adapter. myItemDecoration; import com. taobao. recyclerviewwithrefresh. ui. adapter. mainRecyclerAdapter; import java. util. arrayList; import java. util. list;/*** 1. basic usage of RecyclerView * LayoutManager * ItemAnimator * ItemDecoration ** RecyclerView. adapter * RecyclerView. viewHolder ** 2. swipeRefreshLayout usage ** 3. add the Event Response Method to each item in RecyclerView ** 4. controls the RecyclerView to scroll to a specific position: RecyclerView # scrollToPosition *****/public class MainActivity extends ActionBarActivity implements SwipeRefreshLayout. onRefreshListener {private RecyclerView mRecyclerView; private response listener; private LinearLayoutManager mLinearLayoutManager; private MainRecyclerAdapter mAdapter; @ Override protected void onCreate (Bundle savedInstanceState. onCreate (savedInstanceState); setContentView (R. layout. activity_main); mRecyclerView = (RecyclerView) findViewById (R. id. recyclerView); mRefreshlayout = (SwipeRefreshLayout) findViewById (R. id. refreshLayout); mRefreshlayout. setOnRefreshListener (this); mLinearLayoutManager = new LinearLayoutManager (this); mAdapter = new MainRecyclerAdapter (DataSource. generateData (20); mRecyclerView. setAdapter (mAdapter); // each item is highly consistent and can be set to true to Improve the Performance of mRecyclerView. setHasFixedSize (true); mRecyclerView. setLayoutManager (mLinearLayoutManager); // separation line mRecyclerView. addItemDecoration (new MyItemDecoration (this); // Add a response event mAdapter for each item. setOnItemClickListener (new MainRecyclerAdapter. onItemClickListener () {@ Override public void OnItemClick (View view, String data) {Toast. makeText (MainActivity. this, "data:" + data, Toast. LENGTH_SHORT ). show () ;}}) ;}@ Override public void onRefresh () {new updatetask(.exe cute ();} private class UpdateTask extends AsyncTask <Void, Void, list <String >>{@ Override protected List <String> doInBackground (Void... params) {try {Thread. sleep (2000);} catch (InterruptedException e) {e. printStackTrace () ;}list <String> strings = new ArrayList <> (); strings. add ("new data 1"); strings. add ("new data 2"); strings. add ("new data 3"); strings. add ("new data 4"); return strings ;}@ Override protected void onPostExecute (List <String> strings) {mAdapter. addItems (strings); // the notification is refreshed. setRefreshing (false); // scroll to the column header ---> This is a convenient api that can slide to the specified position of the mRecyclerView. scrollToPosition (0) ;}@override public boolean onCreateOptionsMenu (Menu menu) {getMenuInflater (). inflate (R. menu. menu_main, menu); return true;} @ Override public boolean onOptionsItemSelected (MenuItem item) {// Handle action bar item clicks here. the action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest. xml. int id = item. getItemId (); // noinspection SimplifiableIfStatement if (id = R. id. action_grid) {this. startActivity (new Intent (this, GridActivity. class); return true;} else if (id = R. id. action_settings) {Toast. makeText (MainActivity. this, "run... ", Toast. LENGTH_SHORT ). show (); return true;} return super. onOptionsItemSelected (item );}}






Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.