How to Use RecyclerView (3 ),

Source: Internet
Author: User

How to Use RecyclerView (3 ),

In the previous article (detailed description of RecyclerView (II), we introduced the multi-Item layout Implementation of RecyclerView. Next we will talk about the Cursor Implementation of RecyclerView. Compared with the previous implementation, cursor has more application scenarios and is more common. In particular, it works with LoaderManager and CursorLoader to cache and load and display data. Based on this, we will focus on how to implement the CursorAdapter of RecyclerView.

1. Implement CursorAdapter (with LoaderManager and CursorLoader)

If you have previously used ListView to implement this function (CursorAdapter), you must be familiar with the following two methods:

@Overridepublic View newView(Context context, Cursor cursor, ViewGroup parent) {return null;}@Overridepublic void bindView(View view, Context context, Cursor cursor) {}

Here, the newView method is used to create the Item layout, bindView? The method is used to bind the current View data, which is equivalent to the previous getView method split into two methods.

If you use RecyclerView, you will find that the CursorAdapter class is gone. Since there is no more, we will follow the ListView CursorAdapter class to implement it ourselves. The specific code has no major difference, it is nothing more than registering two observers to listen to changes in the database data. But there are two points to note: one is hasStableIds ()? This method RecyclerView. Adapter cannot rewrite the parent class method. You need to call setHasStableIds (true) during initialization );? To complete the same function, the second is policydatasetinvalidated ()? This method does not exist. It is changed to yydatasetchanged ()? Method.

Void init (Context context, Cursor c, int flags) {boolean cursorPresent = c! = Null; mCursor = c; mDataValid = cursorPresent; mContext = context; mRowIDColumn = cursorPresent? C. getColumnIndexOrThrow ("_ id"):-1; if (flags & callback) = callback) {mChangeObserver = new ChangeObserver (); mDataSetObserver = new MyDataSetObserver ();} else {mChangeObserver = null; mDataSetObserver = null;} if (cursorPresent) {if (mChangeObserver! = Null) c. registerContentObserver (mChangeObserver); if (mDataSetObserver! = Null) c. registerDataSetObserver (mDataSetObserver);} setHasStableIds (true); // pay attention to this topic, you need to set the table Association ID to true} // ************* // public Cursor swapCursor (Cursor newCursor) {if (newCursor = mCursor) {return null;} Cursor oldCursor = mCursor; if (oldCursor! = Null) {if (mChangeObserver! = Null) oldCursor. unregisterContentObserver (mChangeObserver); if (mDataSetObserver! = Null) oldCursor. unregisterDataSetObserver (mDataSetObserver);} mCursor = newCursor; if (newCursor! = Null) {if (mChangeObserver! = Null) newCursor. registerContentObserver (mChangeObserver); if (mDataSetObserver! = Null) newCursor. registerDataSetObserver (mDataSetObserver); mRowIDColumn = newCursor. getColumnIndexOrThrow ("_ id"); mDataValid = true; // configure y the observers about the new cursorpolicydatasetchanged ();} else {mRowIDColumn =-1; mDataValid = false; // configure y the observers about the lack of a data set // There is no policydatasetinvalidated () method in RecyclerView. adapterpolicydatasetchanged (); // note here} return oldCursor ;} // ************ // private class MyDataSetObserver extends DataSetObserver {@ Overridepublic void onChanged () {mDataValid = true; policydatasetchanged ();} @ Overridepublic void onInvalidated () {mDataValid = false; // There is no policydatasetinvalidated () method in RecyclerView. adapterpolicydatasetchanged (); // note here }}

How about it? Is it very simple? Yes, it is so simple. Here is the complete base‑actrecyclecursoradapter Code. Its usage is consistent with that of the ListView CursorAdapter. For details, refer to my Recyclerview LoaderManager Provider.

Ii. Item animation implementation

RecyclerView has already implemented the ITEM animation. You only need to call the following functions to add or delete the Item to see the default animation.

     notifyItemChanged(int)notifyItemInserted(int)notifyItemRemoved(int)notifyItemRangeChanged(int, int)notifyItemRangeInserted(int, int)notifyItemRangeRemoved(int, int)

Is it easy? If you are not satisfied with the system default animation, you can customize the RecyclerView. itemAnimator interface method. For the implementation code, see DefaultItemAnimator. of course, it doesn't matter if you don't want to implement it by yourself. Someone has already written an open-source library. You can go to recyclerview-animators. Here, the default animation implementation method code AnimFragment is provided.

3. nested RecycleView

Generally, nested RecycleView is not recommended, which is similar to ListView. When such a View needs to be nested, you generally want to avoid other methods, such as dynamic AddView, you can also use the MultipleItemAdapter of RecycleView to set different ItemType la s for different views, but sometimes it is free and troublesome to directly use nested la S, different from the ListView implementation method, the implementation of ListView generally inherits the ListView and then returns the onMeasure method, as shown below:

@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);super.onMeasure(widthMeasureSpec, expandSpec);}

However, the implementation method of RecycleView is not to inherit RecycleView, but to modify LayoutManager, that is, by inheriting LinearLayoutManager? GridLayoutManager? StaggeredGridLayoutManager:

FullyLinearLayoutManager

Private int [] mMeasuredDimension = new int [2]; @ Overridepublic void onMeasure (RecyclerView. recycler recycler, RecyclerView. state state, int widthSpec, int heightSpec) {final int widthMode = View. measureSpec. getMode (widthSpec); final int heightMode = View. measureSpec. getMode (heightSpec); final int widthSize = View. measureSpec. getSize (widthSpec); final int heightSize = View. measureSpec. getSize (heightSpec); Log. I (TAG, "onMeasure called. \ nwidthMode "+ widthMode +" \ nheightMode "+ heightSpec +" \ nwidthSize "+ widthSize +" \ nheightSize "+ heightSize +" \ ngetItemCount () "+ getItemCount ()); int width = 0; int height = 0; for (int I = 0; I <getItemCount (); I ++) {measureScrapChild (recycler, I, View. measureSpec. makeMeasureSpec (I, View. measureSpec. UNSPECIFIED), View. measureSpec. makeMeasureSpec (I, View. meas UreSpec. UNSPECIFIED), mMeasuredDimension); if (getOrientation () = HORIZONTAL) {width = width + mMeasuredDimension [0]; if (I = 0) {height = mMeasuredDimension [1] ;}} else {height = height + mMeasuredDimension [1]; if (I = 0) {width = mMeasuredDimension [0] ;}} switch (widthMode) {case View. measureSpec. EXACTLY: width = widthSize; case View. measureSpec. AT_MOST: case View. measureSpec. UNSPECIFIED:} switch (heig HtMode) {case View. measureSpec. EXACTLY: height = heightSize; case View. measureSpec. AT_MOST: case View. measureSpec. UNSPECIFIED:} setMeasuredDimension (width, height);} private void measureScrapChild (RecyclerView. recycler recycler, int position, int widthSpec, int heightSpec, int [] measuredDimension) {try {View view = recycler. getViewForPosition (0); // If IndexOutOfBoundsExceptionif (view! = Null) {RecyclerView. layoutParams p = (RecyclerView. layoutParams) view. getLayoutParams (); int childWidthSpec = ViewGroup. getChildMeasureSpec (widthSpec, getPaddingLeft () + getPaddingRight (), p. width); int childHeightSpec = ViewGroup. getChildMeasureSpec (heightSpec, getPaddingTop () + getPaddingBottom (), p. height); view. measure (childWidthSpec, childHeightSpec); measuredDimension [0] = view. getMeasuredWidth () + p. leftMargin + p. rightMargin; measuredDimension [1] = view. getMeasuredHeight () + p. bottomMargin + p. topMargin; recycler. recycleView (view) ;}} catch (Exception e) {e. printStackTrace ();} finally {}}

FullyGridLayoutManager

Private int [] mMeasuredDimension = new int [2]; @ Overridepublic void onMeasure (RecyclerView. recycler recycler, RecyclerView. state state, int widthSpec, int heightSpec) {final int widthMode = View. measureSpec. getMode (widthSpec); final int heightMode = View. measureSpec. getMode (heightSpec); final int widthSize = View. measureSpec. getSize (widthSpec); final int heightSize = View. measureSpec. getSize (heightSpec ); Int width = 0; int height = 0; int count = getItemCount (); int span = getSpanCount (); for (int I = 0; I <count; I ++) {measureScrapChild (recycler, I, View. measureSpec. makeMeasureSpec (I, View. measureSpec. UNSPECIFIED), View. measureSpec. makeMeasureSpec (I, View. measureSpec. UNSPECIFIED), mMeasuredDimension); if (getOrientation () = HORIZONTAL) {if (I % span = 0) {width = width + mMeasuredDimension [0];} if (I = 0) {height = mMeasuredDimension [1] ;}} else {if (I % span = 0) {height = height + mMeasuredDimension [1];} if (I = 0) {width = mMeasuredDimension [0] ;}}switch (widthMode) {case View. measureSpec. EXACTLY: width = widthSize; case View. measureSpec. AT_MOST: case View. measureSpec. UNSPECIFIED:} switch (heightMode) {case View. measureSpec. EXACTLY: height = heightSize; case View. measureSpec. AT_MOST: case View. M EasureSpec. UNSPECIFIED:} setMeasuredDimension (width, height);} private void measureScrapChild (RecyclerView. recycler recycler, int position, int widthSpec, int heightSpec, int [] measuredDimension) {if (position <getItemCount () {try {View view = recycler. getViewForPosition (0); // If IndexOutOfBoundsExceptionif (view! = Null) {RecyclerView. layoutParams p = (RecyclerView. layoutParams) view. getLayoutParams (); int childWidthSpec = ViewGroup. getChildMeasureSpec (widthSpec, getPaddingLeft () + getPaddingRight (), p. width); int childHeightSpec = ViewGroup. getChildMeasureSpec (heightSpec, getPaddingTop () + getPaddingBottom (), p. height); view. measure (childWidthSpec, childHeightSpec); measuredDimension [0] = view. getMeasuredWidth () + p. leftMargin + p. rightMargin; measuredDimension [1] = view. getMeasuredHeight () + p. bottomMargin + p. topMargin; recycler. recycleView (view) ;}} catch (Exception e) {e. printStackTrace ();}}}
4. as follows:

Item default animation effect

Nested ScrollView Effect

 

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.