Recylerview load and pull-down refresh implementation, recylerview Load

Source: Internet
Author: User

Recylerview load and pull-down refresh implementation, recylerview Load

Pull and load recylerview,Pull-down refresh,When the recylerview is GridLayout, the setting shows that footView [displays a loading layout] occupies a full row.,And listen for recylerview to slide to the last entry to load data.

When using Recylerview to display data, it is impossible to obtain all the data at a time, but to obtain the data from the network as much as the user needs, therefore, when sliding to the last piece of data in RecylerView, more data is loaded.

For example:

First, let's talk about pull-down Refresh:

Set SwipeRefreshLayout on the outer layer of RecylerView, and add the listener to SwipeRefreshLayout:

Display when the code is refreshed with the Listener Control:

MRefreshLayout = view. findViewById (R. id. swipeRefresh); // you can specify the mRefreshLayout color. setColorSchemeResources (android. r. color. holo_blue_light, android. r. color. holo_red_light, android. r. color. holo_orange_light, android. r. color. holo_green_light); mRefreshLayout. setOnRefreshListener (this); // Add a listener and override the onFresh () method.

As you can see,When the pull-down is enabled, onRefresh will be triggered, and then I control it through mRefreahLayout. setRefreshing (true) to display the refresh

Then, in onPostExecute, that is, after the network request data is complete, the refresh is stopped through setRefreshing (false), and the refreshing ydatachanged ().

Pull up and load

First, we define two la S. One isNormal item Layout, One isPrompt for loading layout:

Normal item layout:

The following message is displayed:

Then create two ViewHolder:

Override getItemViewType,

If slide to the last entry, the system returns FootView (defined int variable with a value of 1). Otherwise, the system returns normal NormalView (with a value of 0 ).

In onCreateViewHolder, determine which layout to load based on viewType:

ThenIn onBindViewHolder, different content is displayed based on the holder type. [Normal item content or loading prompt content is displayed]

Because you finally display the last multi-display footView, more than 1 is required in getItemCount;

.

In this way,When an item is displayed, different ViewHolder is returned Based on the type returned by itemType, and different content is displayed based on different holder values in onBindViewHolder. Therefore, in the last item, the loaded layout is displayed. Otherwise, the normal item layout is displayed.

Then, because I am GridLayoutManager, set it to occupy three columns when displaying the loaded layout. The rest just make it occupy one column.:

Determines the number of columns based on whether the position is the last one.

Add a sliding listener in recylerview. load more data if it is the last one:

Complete code:

Public class Fragment_Movie_Types extends Fragment implements SwipeRefreshLayout. onRefreshListener {private static String TAG = "listener"; private RecyclerView mRecyclerView; private SwipeRefreshLayout mRefreshLayout; private String tag; private int lastItemPosition; // The Position of the last item is private int mCurrentStart = 0; // request the starting position of the movie private int NormalView = 0; // normal item private int FootView = 1; // load view private List
 
  
MMovieInfos = new ArrayList <> (); private TypeAdapter adapter; public int mMovieType; // movie type/* 1. love article * 2. comedy * 3. animation * 4. sci-Fi * 5. action * 6. classic **/public Fragment newInstance (int movieType) {Fragment_Movie_Types fragment = new Fragment_Movie_Types (); fragment. mMovieType = movieType; return fragment;} @ Override public void onCreate (@ Nullable Bundle savedInstanceState) {super. onCreate (savedInstanceState); adapter = new TypeAdapter (); Log. I (TAG, "mMovieType ==>" + mMovieType +" onCreate "); Log. I (TAG, "mMovieType ==>" + this. mMovieType); switch (this. mMovieType) {case 1: tag = "love"; break; case 2: tag = "Comedy"; break; case 3: tag = "Animation"; break; case 4: tag = "sci-fi"; break; case 5: tag = "action"; break; case 6: tag = "classic"; break;} Log. I (TAG, "tag =>" + tag); AsyncTask
  
   
> Task = new AsyncTask
   
    
> () {@ Override protected List
    
     
DoInBackground (String... strings) {return new FetchMovies (). getMoviesByTag (tag, mCurrentStart) ;}@ Override protected void onPostExecute (List
     
      
MovieInfos) {super. onPostExecute (movieInfos); mMovieInfos = movieInfos; adapter. yydatasetchanged (); Log. I (TAG, "Network request ended") ;}}; task.exe cute (); setRetainInstance (true) ;}@ Nullable @ Override public View onCreateView (LayoutInflater inflater, @ Nullable ViewGroup container, @ Nullable Bundle savedInstanceState) {View view = inflater. inflate (R. layout. fragment_movie_types, container, false); mRecycl ErView = view. findViewById (R. id. recyler_view); mRefreshLayout = view. findViewById (R. id. swipeRefresh); mRefreshLayout. setColorSchemeResources (android. r. color. holo_blue_light, android. r. color. holo_red_light, android. r. color. holo_orange_light, android. r. color. holo_green_light); mRefreshLayout. setOnRefreshListener (this); final GridLayoutManager lm = new GridLayoutManager (getActivity (), 3); lm. setSpanS IzeLookup (new GridLayoutManager. spanSizeLookup () {// if it is the last item, it occupies three columns; otherwise, it occupies one column @ Override public int getSpanSize (int position) {boolean isFooter = position = adapter. getItemCount ()-1; return isFooter? 3: 1 ;}}); mRecyclerView. setLayoutManager (lm); mRecyclerView. setAdapter (adapter); mRecyclerView. addOnScrollListener (new RecyclerView. onScrollListener () {@ Override public void onScrollStateChanged (RecyclerView recyclerView, int newState) {super. onScrollStateChanged (recyclerView, newState); // Log. d (TAG, "current state =>" + newState); if (newState = RecyclerView. SCROLL_STATE_IDLE) {Log. d (TAG, "SCROLL_STATE_IDEL"); if (lastItemPosition + 1 = lm. getItemCount () {// Log. d (TAG, "loading more"); mCurrentStart ++; loadMore () ;}}@ Override public void onScrolled (RecyclerView recyclerView, int dx, int dy) {super. onScrolled (recyclerView, dx, dy); // Log. d (TAG, "onScrolled"); lastItemPosition = lm. findLastVisibleItemPosition () ;}}); return view ;}@ Override public void onRefresh () {mRefreshLayout. setRefreshing (true); AsyncTask
      
        > Task = new AsyncTask
       
         > () {@ Override protected List
        
          DoInBackground (String... strings) {return new FetchMovies (). getMoviesByTag (tag, 0) ;}@ Override protected void onPostExecute (List
         
           MovieInfos) {super. onPostExecute (movieInfos); mMovieInfos. clear (); mMovieInfos = movieInfos; adapter. yydatasetchanged (); mRefreshLayout. setRefreshing (false); Log. I (TAG, "Network request ended") ;}; task.exe cute () ;} public class TypeAdapter extends RecyclerView. adapter
          
            {@ Override public ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {LayoutInflater inflater = LayoutInflater. from (getActivity (); if (viewType = NormalView) {View v = inflater. inflate (R. layout. movie_item, parent, false); return new TypeHolder (v);} else {View v = inflater. inflate (R. layout. footview, parent, false); return new FootHolder (v) ;}@override public void onBindViewHolde R (ViewHolder holder, int position) {if (holder instanceof TypeHolder) {(TypeHolder) holder ). movieName. setText (mMovieInfos. get (position ). getName (); Picasso. with (getActivity ()). load (mMovieInfos. get (position ). getImgUrl ()). into (TypeHolder) holder ). movieImg);} else {(FootHolder) holder ). mTip. setText ("loading... ") ;}@ Override public int getItemCount () {if (mMovieInfos! = Null) {return mMovieInfos. size () + 1 ;}else {return 0 ;}@ Override public int getItemViewType (int position) {if (position + 1 = getItemCount () {return FootView ;} else {return NormalView;} class TypeHolder extends ViewHolder {// holder public ImageView movieImg; public LinearLayout starContainer; public TextView movieName; public TypeHolder (View itemView) {super (itemView); movieImg = itemView. findViewById (R. id. movie_img); movieName = itemView. findViewById (R. id. movie_name); starContainer = itemView. findViewById (R. id. star_container) ;}} class FootHolder extends ViewHolder {// the loading holder public TextView mTip is prompted; public FootHolder (View itemView) {super (itemView); mTip = itemView. findViewById (R. id. TV _tip) ;}} private void loadMore () {final AsyncTask
           
             > Task = new AsyncTask
            
              > () {@ Override protected List
             
               DoInBackground (String [] objects) {return new FetchMovies (). getMoviesByTag (tag, mCurrentStart * 20);} @ Override protected void onPostExecute (List
              
                O) {super. onPostExecute (o); mMovieInfos. addAll (o); adapter. notifyDataSetChanged () ;}}; task.exe cute ();}}
              
             
            
           
          
         
        
       
      
     
    
   
  
 


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.