1. 程式人生 > >XrecyclerView實現上拉載入和下拉重新整理+多條目(MVP獲取資料)

XrecyclerView實現上拉載入和下拉重新整理+多條目(MVP獲取資料)

依賴

implementation('com.jcodecraeer:xrecyclerview:1.5.9') {
    exclude group: 'com.android.support'
}
implementation 'com.android.support:recyclerview-v7:28.0.0'

圖片載入依賴

implementation 'com.github.bumptech.glide:glide:4.8.0'

Activity

public class ShoppingActivity extends AppCompatActivity implements 						 
XRecyclerView.LoadingListener, DataCall<List<Goods>>{

private XRecyclerView xRecyclerView;
private GoodsListAdapter goodsListAdapter;
private GoodsListPresenter goodsListPresenter = new GoodsListPresenter(this);

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_shopping);
	//獲取控制元件
    xRecyclerView = findViewById(R.id.rv);
	
    xRecyclerView.setLoadingListener(this);
	//建立StaggeredGridLayoutManager 
    StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);

    xRecyclerView.setLayoutManager(staggeredGridLayoutManager);
	//建立介面卡
    goodsListAdapter = new GoodsListAdapter(ShoppingActivity.this);

    xRecyclerView.setAdapter(goodsListAdapter);
    //載入資料
    xRecyclerView.refresh();

}

@Override
public void onRefresh() {
    goodsListPresenter.request(true);
}

@Override
public void onLoadMore() {
    goodsListPresenter.request(false);
}

@Override
public void success(List<Goods> data) {

    xRecyclerView.refreshComplete();
    xRecyclerView.loadMoreComplete();

    if (goodsListPresenter.isResresh()) {
        goodsListAdapter.clearList();
    }
    goodsListAdapter.addAll(data);

    goodsListAdapter.notifyDataSetChanged();
}

@Override
public void fail(User user) {
    Toast.makeText(ShoppingActivity.this, user.getCode() + "  " + user.getMsg(),
            Toast.LENGTH_LONG).show();
}
@Override
protected void onDestroy() {
    super.onDestroy();
    
    goodsListPresenter.unBindCall();//防止記憶體洩漏
}
}

Presenter(P層)

public class GoodsListPresenter extends BasePresenter {
private int page = 1;
private boolean isRefresh = true;

public GoodsListPresenter(DataCall dataCall) {
    super(dataCall);
}
@Override
protected User getData(Object... args) {

    isRefresh = (boolean) args[0];//是否需要重新整理

    if (isRefresh) {

        page = 1;
    }else {
        page++;
    }
    User user = GoodsListModel.goodsList(page+"");

    return user;
}
public boolean isResresh() {

    return isRefresh;
}
}

抽象類

public abstract class BasePresenter {

DataCall dataCall;

public BasePresenter(DataCall dataCall) {
    this.dataCall = dataCall;
}

private Handler mHandler = new Handler(Looper.getMainLooper()) {
    @Override
    public void handleMessage(Message msg) {

        User user = (User)msg.obj;

        if (user.getCode().equals("0")) {
            dataCall.success(user.getData());
        } else {
            dataCall.fail(user);
        }
    }
};

/**
 * activity或者fragment只需關心request方法
 * request呼叫抽象方法useModel()方法
 */
public void request(final Object... args) {

    new Thread(new Runnable() {
        @Override
        public void run() {

            Message message = mHandler.obtainMessage();
            message.obj = getData(args);
            mHandler.sendMessage(message);

        }
    }).start();
}

protected abstract Object getData(Object...args);

public void unBindCall(){
    this.dataCall = null;
}
}

Model(M層)

public class GoodsListModel {

public static User goodsList(String page) {
    String resultString = Utils.postForm("http://www.zhaoapi.cn/product/getProducts",
            new String[]{"pscid","page"},new String[]{"1",page});
    Gson gson = new Gson();
    Type type = new TypeToken<User<List<Goods>>>(){}.getType();
    User user = gson.fromJson(resultString, type);
    return user;
}
}

View (V層)

import com.zhao.demo.bean.User;

public interface DataCall<T> {

void success(T data);

void fail(User user);

}

Adapter(介面卡)

public class GoodsListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

public static final int TYPE_RIGHT_IMAGE =0;
public static final int TYPE_THREE_IMAGE = 1;

private List<Goods> mList = new ArrayList<>();
private Context context;

public GoodsListAdapter(Context context) {
    this.context = context;

}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
	//判斷條目型別
    if (i == TYPE_RIGHT_IMAGE) {
    
        View view = View.inflate(context, R.layout.activity_shopping_item_image, null);
        return new GoodHolderView_image(view);
        
    }else {
    
        View view = View.inflate(context, R.layout.activity_shopping_item_text,null);
        return new GoodHolderView_Text(view);
        
    }

}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int i) {
	
    if (holder instanceof GoodHolderView_image) {
    
    	//由於我們的資料圖片提供的不標準,所以我們需要切割得到圖片
        String imageurl = "https"+mList.get(i).getImages().split("https")[1];
        Log.i("dt","imageUrl: "+imageurl);
        imageurl = imageurl.substring(0,imageurl.lastIndexOf(".jpg")+".jpg".length());
        
        Glide.with(context).load(imageurl).into(((GoodHolderView_image) holder).imageView);//載入圖片
    }

    if (holder instanceof GoodHolderView_Text) {
        ((GoodHolderView_Text) holder).textView.setText(mList.get(i).getTitle());
        
        String imageurl = "https"+mList.get(i).getImages().split("https")[1];
        imageurl = imageurl.substring(0,imageurl.lastIndexOf(".jpg")+".jpg".length());
        
        Glide.with(context).load(imageurl).into(((GoodHolderView_Text) holder).imageView);
    }

}

public int getItemCount() {
    return mList.size();
}

@Override
public int getItemViewType(int position) {

    Goods goods = mList.get(position);
//返回條目型別,可以根據需要返回條目型別,我這就隨意返回了兩種,
    return goods.getPid()% 2;
}
public void clearList() {
    mList.clear();
}
public void addAll(List<Goods> data) {
//新增資料
    mList.addAll(data);
}

class GoodHolderView_image extends RecyclerView.ViewHolder {
    ImageView imageView;
    public GoodHolderView_image(@NonNull View itemView) {
        super(itemView);

        imageView = itemView.findViewById(R.id.image_item);
    }
}
class GoodHolderView_Text extends RecyclerView.ViewHolder {
    ImageView imageView;
    TextView textView;
    public GoodHolderView_Text(@NonNull View itemView) {
        super(itemView);
        textView = itemView.findViewById(R.id.textView);
        imageView = itemView.findViewById(R.id.images);
    }
}
}