1. 程式人生 > >item中有圖片載入時,讓RecyclerView滑動更流暢

item中有圖片載入時,讓RecyclerView滑動更流暢

RecyclerView 為了滑動更加流暢,滑動時停止載入圖片,反之滑動停止時載入圖片。 則對RecyclerView 進行重寫:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

import com.bumptech.glide.Glide;

public class XRecyclerView extends RecyclerView {
    public XRecyclerView(Context context) {
        this(context, null); 
     } 
 
    public XRecyclerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0); 
     } 
 
    public XRecyclerView(Context context, AttributeSet attrs, int defStyle) { 
        super(context, attrs, defStyle); 
         init(); 
     } 
 
    private void init() { 
        addOnScrollListener(new ImageAutoLoadScrollListener()); 
     } 
 
    //監聽滾動來對圖片載入進行判斷處理 
     public class ImageAutoLoadScrollListener extends OnScrollListener{ 
 
        @Override 
         public void onScrolled(RecyclerView recyclerView, int dx, int dy) { 
            super.onScrolled(recyclerView, dx, dy); 
         } 
 
        @Override 
         public void onScrollStateChanged(RecyclerView recyclerView, int newState) { 
            super.onScrollStateChanged(recyclerView, newState); 
             switch (newState){ 
                case SCROLL_STATE_IDLE: // The RecyclerView is not currently scrolling. 
                     //當螢幕停止滾動,載入圖片 
                     try { 
                        if(getContext() != null) Glide.with(getContext()).resumeRequests();
                    } 
                    catch (Exception e) { 
                        e.printStackTrace(); 
                     } 
                    break; 
                 case SCROLL_STATE_DRAGGING: // The RecyclerView is currently being dragged by outside input such as user touch input. 
                     //當螢幕滾動且使用者使用的觸碰或手指還在螢幕上,停止載入圖片 
                     try { 
                        if(getContext() != null) Glide.with(getContext()).pauseRequests(); 
                     } 
                    catch (Exception e) { 
                        e.printStackTrace(); 
                     } 
                    break; 
                 case SCROLL_STATE_SETTLING: // The RecyclerView is currently animating to a final position while not under outside control. 
                     //由於使用者的操作,螢幕產生慣性滑動,停止載入圖片 
                     try { 
                        if(getContext() != null) Glide.with(getContext()).pauseRequests(); 
                     } 
                    catch (Exception e) { 
                        e.printStackTrace(); 
                     } 
                    break; 
             } 
        } 
    } 
}