This article RecyclerViewDemo




RecyclerView three own layout

This article image interface from dry goods concentration camp gank. IO/API

RecyclerView is a control in support.v7 package, which can be said to be an enhanced and upgraded version of ListView and GridView.

RecyclerView official description of RecyclerView (not because OF my Poor English, really) :

A flexible view for providing a limited window into a large data set.

RecyclerView has been in use for a long time since it was released in 2014.

This paper mainly introduces the basic use of RecyclerView, automatic loading more data, item drag and swipe delete. Detailed effect and use of my demo;

RecyclerView basic usage

RecyclerView is similar to ListView. I’ll use grid layout as an example, but I’ll go into the code first.

Start by creating this control in the layout:

    
 



    





    
    

Copy the code

The code for the Activity is as follows:

public class GridActivity extends AppCompatActivity { private static RecyclerView recyclerview; private CoordinatorLayout coordinatorLayout; private GridAdapter mAdapter; private List meizis; private GridLayoutManager mLayoutManager; private int lastVisibleItem ; private int page=1; private ItemTouchHelper itemTouchHelper; private SwipeRefreshLayout swipeRefreshLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_grid); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); initView(); // Initialize the layout setListener(); New GetData().execute("http://gank.io/api/data/ welfare /10/1"); } private void initView(){ coordinatorLayout=(CoordinatorLayout)findViewById(R.id.grid_coordinatorLayout); recyclerview=(RecyclerView)findViewById(R.id.grid_recycler); mLayoutManager=new GridLayoutManager(GridActivity.this,3,GridLayoutManager.VERTICAL,false); / / set for a 3 column vertical grid layout recyclerview. SetLayoutManager (mLayoutManager); swipeRefreshLayout=(SwipeRefreshLayout) findViewById(R.id.grid_swipe_refresh) ; / / the position of the adjusting SwipeRefreshLayout SwipeRefreshLayout. SetProgressViewOffset (false, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics())); } private void setListener () {/ / swipeRefreshLayout refresh to monitor swipeRefreshLayout. SetOnRefreshListener (new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { page=1; New GetData().execute("http://gank.io/api/data/ welfare /10/1"); }}); } private class GetData extends AsyncTask { @Override protected void onPreExecute() { super.onPreExecute(); / / set the swipeRefreshLayout to refresh status swipeRefreshLayout. SetRefreshing (true); } @Override protected String doInBackground(String... params) { return MyOkhttp.get(params[0]); } protected void onPostExecute(String result) { super.onPostExecute(result); if(! TextUtils.isEmpty(result)){ JSONObject jsonObject; Gson gson=new Gson(); String jsonData=null; try { jsonObject = new JSONObject(result); jsonData = jsonObject.getString("results"); } catch (JSONException e) { e.printStackTrace(); } if(meizis==null||meizis.size()==0){ meizis= gson.fromJson(jsonData, new TypeToken>() {}.getType()); Meizi pages=new Meizi(); pages.setPage(page); meizis.add(pages); Else {List more= gson.fromjson (jsonData, new TypeToken>() {}.getType()); meizis.addAll(more); Meizi pages=new Meizi(); pages.setPage(page); meizis.add(pages); If (mAdapter==null){recyclerView. setAdapter(mAdapter = new) GridAdapter(GridActivity.this,meizis)); / / recyclerview adapter / / adapter set custom. Click to monitor mAdapter setOnItemClickListener (new GridAdapter. OnRecyclerViewItemClickListener () { @Override public void onItemClick(View view) { int position=recyclerview.getChildAdapterPosition(view); SnackbarUtil. ShortSnackbar (coordinatorLayout, "click on the" + + "a", the position SnackbarUtil. Info), show (); // Color Snackbar utility class, see my previous article "No time to explain, use Snackbar! http://www.jianshu.com/p/cd1e80e64311} - Android Snackbar fancy use guide @ Override public void onItemLongClick (View View) {} }); } else {/ / let the adapter refresh data mAdapter. NotifyDataSetChanged (); }} / / stop loading animation swipeRefreshLayout swipeRefreshLayout setRefreshing (false); }}}Copy the code

RecyclerView adaptors

public class GridAdapter extends RecyclerView.Adapter implements View.OnClickListener, View.OnLongClickListener { private Context mContext; private List datas; / / / / custom data to monitor events public static interface OnRecyclerViewItemClickListener {void onItemClick (View the View). void onItemLongClick(View view); } private OnRecyclerViewItemClickListener mOnItemClickListener = null; public void setOnItemClickListener(OnRecyclerViewItemClickListener listener) { mOnItemClickListener = listener; Public GridAdapter(Context Context,List datas) {mContext= Context; this.datas=datas; } @override public int getItemViewType(int position) {if (! TextUtils.isEmpty(datas.get(position).getUrl())) { return 0; } else { return 1; } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, ViewHolder if(viewType==0){View View = LayoutInflater. From (mContext) ).inflate(R.layout.grid_meizi_item, parent, false); MyViewHolder holder = new MyViewHolder(view); SetOnClickListener (this); // Set the layout to click and long click on view.setonClickListener (this); view.setOnLongClickListener(this); return holder; }else{ MyViewHolder2 holder2=new MyViewHolder2(LayoutInflater.from( mContext).inflate(R.layout.page_item, parent, false)); Return holder2; // This layout is a textView that displays the page count. }} @override public void onBindViewHolder(recyclerView. ViewHolder holder, int position) { If it's MyViewHolder it loads the network image, If (holder instanceof MyViewHolder){ Picasso.with(mContext).load(datas.get(position).getUrl()).into(((MyViewHolder) holder).iv); Else if(holder instanceof MyViewHolder2){((MyViewHolder2)) Holder). TV. SetText (datas. The get (position). Getpages () + "page"); } } @Override public int getItemCount() { return datas.size(); @override public void onClick(View v) {if (mOnItemClickListener! = null) { mOnItemClickListener.onItemClick(v); } } @Override public boolean onLongClick(View v) { if (mOnItemClickListener! = null) { mOnItemClickListener.onItemLongClick(v); } return false; } class MyViewHolder extends recyclerView. ViewHolder {private ImageButton iv; public MyViewHolder(View view) { super(view); iv = (ImageButton) view.findViewById(R.id.iv); }} class MyViewHolder2 extends RecyclerView.ViewHolder {private TextView TV; public MyViewHolder2(View view) { super(view); tv = (TextView) view.findViewById(R.id.tv); Public void addItem(Meizi Meizi, int position) {meizis.add(position, Meizi); notifyItemInserted(position); recyclerview.scrollToPosition(position); Public void removeItem(final int position) {meizis.remove(position); notifyItemRemoved(position); }}Copy the code

Data types:

public class Meizi { private String url; Private int page; Public String getUrl() {return url; } public void setUrl(String url) { this.url = url; } public int getPage() { return page; } public void setPage(int page) { this.page = page; }}Copy the code

RecyclerView is a lot like ListView.

RecyclerView requires the setLayoutManager() method to set the layout manager, There are three default layout manager RecyclerView LinearLayoutManager, GridLayoutManager, StaggeredGridLayoutManager, support horizontal and vertical alignment and backward sliding. If you want to change RecyclerView to horizontal sliding, you can also call

mLayoutManager.setOrientation(GridLayoutManager.HORIZONTAL);Copy the code

RecyclerView does not provide click listening for items like ListView does, so we have to implement it ourselves. RecyclerView item click event listeners can be set in this article to me for the item of the view, can also be RecyclerView. AddOnItemTouchListener to judge gestures to implement.

You can set the animation when an item is loaded or removed by calling the following method

recyclerView.setItemAnimator(new DefaultItemAnimator());Copy the code

More animations can look at the others write RecyclerViewItemAnimators this project.

Auto load more

To realize automatic loading of the next page when sliding to a certain place in the list (for example, when the last two items are left), you can set the slider listening of RecyclerView to obtain the position of the last item displayed in the adapter. If the position of the item is less than or equal to the total number of adapter items minus 2, the data of the next page will be loaded. The GridLayoutManager and LinearLayoutManager methods are as follows:

/ / recyclerview rolling listening recyclerview. AddOnScrollListener (new recyclerview. OnScrollListener () {@ Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); //0: the screen stops scrolling; 1: The screen is scrolling and the user is still touching or the finger is still on the screen; 2: with the user's operation, the screen generated inertia sliding; // When the sliding state stops and there are less than two items left, Automatically loads the next page if (newState because = = RecyclerView SCROLL_STATE_IDLE && lastVisibleItem + 2 > = mLayoutManager. GetItemCount ()) {new GetData (). The execute (welfare / 10 "http://gank.io/api/data/ /" + + + page ()); } } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); // Gets the location of the last loaded visible view in the adapter. lastVisibleItem = mLayoutManager.findLastVisibleItemPosition(); }});Copy the code

StaggeredGridLayoutManager because the location of the item is interlaced, findLastVisibleItemPosition () method returns an array, so we have to determine the maximum of the array, the above onScrolled method as such

int[] positions= mLayoutManager.findLastVisibleItemPositions(null); lastVisibleItem =Math.max(positions[0],positions[1]); / / set according to StaggeredGridLayoutManager set the number of columnsCopy the code



Automatically load next page.gif

XRecyclerView is a library written by others, to achieve the RecyclerView drop-down head and bottom loading layout, need can see.

Item drag and slide to delete

ItemTouchHelper is a RecyclerView sliding delete and drag helper class, RecyclerView item drag move and slide delete rely on it.

The ItemTouchHelper listens as follows

ItemTouchHelper =new itemTouchHelper (new ItemTouchHelper.callback () {Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { int dragFlags=0,swipeFlags=0; if(recyclerView.getLayoutManager() instanceof StaggeredGridLayoutManager||recyclerView.getLayoutManager() instanceof GridLayoutManager){// The grid layout has four directions dragFlags=ItemTouchHelper.UP|ItemTouchHelper.DOWN|ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT; } else if (recyclerView getLayoutManager () instanceof LinearLayoutManager) {/ / linear type layout has two directions dragFlags=ItemTouchHelper.UP|ItemTouchHelper.DOWN; swipeFlags = ItemTouchHelper.START|ItemTouchHelper.END; } return makeMovementFlags(dragFlags,swipeFlags); @override public Boolean onMove(RecyclerView, RecyclerView); RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { int from=viewHolder.getAdapterPosition(); int to=target.getAdapterPosition(); Collections.swap(meizis,from,to); Madapter. notifyItemMoved(from,to); // Update the position of item in the adapter return true; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, } @override public Boolean isLongPressDragEnabled() {return false; }});Copy the code

ItemTouchHelper needs to be bound to recyclerView to work, and is called when the recyclerView is initialized

     itemTouchHelper.attachToRecyclerView(recyclerview);Copy the code

Since I want the picture item in the grid layout to be dragable and the page item not, I return false from isLongPressDragEnabled() and do the specific processing in the item long click event listener.

mAdapter.setOnItemClickListener(new GridAdapter.OnRecyclerViewItemClickListener() { @Override public void onItemClick(View view) { } @Override public void onItemLongClick(View view) { itemTouchHelper.startDrag(recyclerview.getChildViewHolder(view)); // set drag item}});Copy the code

If you want to animate a drag and slide response for an Item, you can use the following three methods of ItemTouchHelper. With a linear layout example:

// Call @override public void onSelectedChanged(recyclerView. ViewHolder ViewHolder, int actionState) { super.onSelectedChanged(viewHolder, actionState); if(actionState==ItemTouchHelper.ACTION_STATE_DRAG){ viewHolder.itemView.setBackgroundColor(Color.LTGRAY); }} @override public void clearView(RecyclerView, RecyclerView) RecyclerView.ViewHolder viewHolder) { super.clearView(recyclerView, viewHolder); viewHolder.itemView.setBackgroundColor(Color.WHITE); @override public void onChildDraw(Canvas C, RecyclerView, RecyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive); // Modify item transparency according to the sliding offset value of item. Screenwidth viewHolder. I get in advance of the screen width itemView. SetAlpha (1 - Math. Abs (dX)/screenwidth); }Copy the code



Drag and slide to delete.gif

This article RecyclerViewDemo

This article is for the two brothers who came to take over their jobs with me after saying “three hundred and sixty lines.

I know you all like to look at girls.

Please give me a thumbs up if you think this article is ok