本文為菜鳥窩作者劉婷的連載≈鳎”商城項(xiàng)目實(shí)戰(zhàn)”系列來(lái)聊聊仿”京東淘寶的購(gòu)物商城”如何實(shí)現(xiàn)茄蚯。
140套Android優(yōu)秀開(kāi)源項(xiàng)目源碼,領(lǐng)取地址:http://mp.weixin.qq.com/s/afPGHqfdiApALZqHsXbw-A
或歡迎勾搭運(yùn)營(yíng)小姐姐(微信 id:BT474849)免費(fèi)領(lǐng)取哦~
在上篇文章《商城項(xiàng)目實(shí)戰(zhàn) | 8.1 SwipeRefreshLayout 詳解 官方下拉刷新控件》中對(duì) SwipeRefreshLayout 做了詳細(xì)的介紹了闻妓,但是也發(fā)現(xiàn)了該控件有個(gè)問(wèn)題菌羽,那就是它只支持下拉刷新,不支持加載更多由缆,這在使用的時(shí)候就有點(diǎn)麻煩了注祖,所以本篇文章就要對(duì) SwipeRefreshLayout 進(jìn)行擴(kuò)展猾蒂,使用 SwipeRefreshLayout 實(shí)現(xiàn)可以下拉刷新和加載更多的熱門商品列表。
所要實(shí)現(xiàn)的熱門商品列表的效果
SwipeRefreshLayout 具有下拉刷新的功能是晨,但是加載更多則不支持肚菠,所以就要我們自己擴(kuò)展了,本篇文章就介紹 Github 上面開(kāi)源的一款控件 MaterialRefreshLayout署鸡,這款組件在原本官方的控件 SwipeRefreshLayout 上做了擴(kuò)展案糙,不僅可以支持下拉刷新,還可以支持加載更多靴庆。先來(lái)看下熱門商品的效果圖时捌,如下。
[圖片上傳失敗...(image-c731af-1565145810083)]
圖中的熱門商品列表可以下拉刷新數(shù)據(jù)炉抒,同時(shí)還需要加載更多的功能奢讨,如何實(shí)現(xiàn)這樣的熱門商品列表的效果呢?帶著這個(gè)問(wèn)題往下看焰薄。
熱門商品列表實(shí)現(xiàn)過(guò)程
已經(jīng)看到了熱門商品列表的效果拿诸,下面就是具體的實(shí)現(xiàn)過(guò)程了。
1. Gradle 添加依賴
在 module 下的 build.gradle 文件中添加所需第三方控件的依賴塞茅。
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support.constraint:constraint-layout:1.0.1'
testCompile 'junit:junit:4.12'
compile 'com.daimajia.slider:library:1.1.5@aar'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.android.support:support-v4:25.2.0'
compile 'com.android.support:recyclerview-v7:25.2.0'
compile 'com.android.support:cardview-v7:25.2.0'
compile 'com.squareup.okhttp3:okhttp:3.6.0'
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.github.d-max:spots-dialog:0.7'
compile 'com.facebook.fresco:fresco:1.2.0'
compile 'com.cjj.materialrefeshlayout:library:1.3.0'
}
2. 添加權(quán)限
因?yàn)檫@里需要從網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù)亩码,所以需要網(wǎng)絡(luò)權(quán)限。
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
3. 定義布局
根據(jù)效果圖來(lái)設(shè)計(jì) RecyclerView 的 item 布局以及 熱門模塊 HotFragment 的布局野瘦。
首先是新建 xml 布局文件 fragment_hot_layout.xml描沟,也就是熱門模塊 HotFragment 的布局,如下鞭光。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.cjj.MaterialRefreshLayout
android:id="@+id/hot_layout_refresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
app:overlay="true"
app:wave_show="true"
app:wave_color="#90ffffff"
app:progress_colors="@array/material_colors"
app:wave_height_type="higher"
>
<android.support.v7.widget.RecyclerView
android:id="@+id/hot_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</com.cjj.MaterialRefreshLayout>
</LinearLayout>
然后就是RecyclerView 的 item 布局了吏廉。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/selector_list_item"
android:padding="5dp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.facebook.drawee.view.SimpleDraweeView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:background="@null"
android:id="@+id/drawee_view"
android:layout_alignParentLeft="true"
app:viewAspectRatio="1"
>
</com.facebook.drawee.view.SimpleDraweeView>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_toRightOf="@+id/drawee_view">
<TextView
android:id="@+id/text_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/black"
android:textSize="16sp"
android:maxLines="3"
/>
<TextView
android:id="@+id/text_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textColor="@color/firebrick"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/bigRedButton"
android:layout_marginTop="20dp"
android:text="立即購(gòu)買"
android:layout_gravity="right|bottom"
/>
</LinearLayout>
</RelativeLayout>
這里圖片加載組件使用的是 Facebook 開(kāi)源的圖片加載組件 Fresco。
4. 初始化 Fresco 類
因?yàn)槭褂昧藞D片加載組件 Fresco惰许,所以必須在 Application 中做對(duì) Fresco 類初始化的處理席覆。
public class CNiaoApplicaiton extends Application {
@Override
public void onCreate() {
super.onCreate();
Fresco.initialize(this);
}
}
5. 定義實(shí)體類
根據(jù)所要請(qǐng)求的數(shù)據(jù)定義好相應(yīng)的實(shí)體類,這里涉及了兩個(gè)實(shí)體類汹买,分別為 WaresInfo 商品信息類以及 PageInfo 頁(yè)面信息類佩伤。
WaresInfo 商品信息類如下。
public class WaresInfo implements Serializable{
private Long id;
private String name;
private String imgUrl;
private String description;
private Float price;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
}
下面就是 PageInfo 頁(yè)面信息類卦睹。
public class PageInfo <T> implements Serializable{
private int currentPage;
private int pageSize;
private int totalPage;
private int totalCount;
private List<T> list;
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
6. 定義 Adapter
RecyclerView 作為列表控件畦戒,必定需要適配器 Adapter,下面是定義的 HotWaresAdapter结序。
public class HotWaresAdapter extends RecyclerView.Adapter<HotWaresAdapter.ViewHolder> {
private List<WaresInfo> mDatas;
private LayoutInflater mInflater;
public HotWaresAdapter(List<WaresInfo> wares){
mDatas = wares;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
mInflater = LayoutInflater.from(parent.getContext());
View view = mInflater.inflate(R.layout.recycler_item_wares_layout,null);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
WaresInfo wares = getData(position);
holder.draweeView.setImageURI(Uri.parse(wares.getImgUrl()));
holder.textTitle.setText(wares.getName());
holder.textPrice.setText("¥"+wares.getPrice());
}
public WaresInfo getData(int position){
return mDatas.get(position);
}
public List<WaresInfo> getDatas(){
return mDatas;
}
public void clearData(){
mDatas.clear();
notifyItemRangeRemoved(0,mDatas.size());
}
public void addData(List<WaresInfo> datas){
addData(0,datas);
}
public void addData(int position,List<WaresInfo> datas){
if(datas !=null && datas.size()>0) {
mDatas.addAll(datas);
notifyItemRangeChanged(position, mDatas.size());
}
}
@Override
public int getItemCount() {
if(mDatas!=null && mDatas.size()>0)
return mDatas.size();
return 0;
}
class ViewHolder extends RecyclerView.ViewHolder{
SimpleDraweeView draweeView;
TextView textTitle;
TextView textPrice;
public ViewHolder(View itemView) {
super(itemView);
draweeView = (SimpleDraweeView) itemView.findViewById(R.id.drawee_view);
textTitle= (TextView) itemView.findViewById(R.id.text_title);
textPrice= (TextView) itemView.findViewById(R.id.text_price);
}
}
}
在 Adapter 中寫入了 clearData() 清除數(shù)據(jù)以及 addData(List<WaresInfo> datas) 添加數(shù)據(jù)的方法障斋,為之后刷新數(shù)據(jù)和加載更多數(shù)據(jù)時(shí)調(diào)用。
7. 定義獲取數(shù)據(jù)的方法
布局、實(shí)體類還有適配器都已經(jīng)寫好了垃环,下面就是要開(kāi)始寫請(qǐng)求數(shù)據(jù)的方法了邀层。
private void getData(){
String url = Constants.API.WARES_HOT+"?curPage="+currPage+"&pageSize="+pageSize;
httpHelper.get(url, new SpotsCallBack<PageInfo<WaresInfo>>(getContext()) {
@Override
public void onSuccess(Response response, PageInfo<WaresInfo> waresPage) {
datas = waresPage.getList();
currPage = waresPage.getCurrentPage();
totalPage =waresPage.getTotalPage();
showData();
}
@Override
public void onError(Response response, int code, Exception e) {
Toast.makeText(getActivity(),"Error:"+code+e.toString(),Toast.LENGTH_SHORT).show();
super.onError(response,code,e);
}
@Override
public void onFailure(Request request, Exception e) {
super.onFailure(request, e);
Toast.makeText(getActivity(),"Fail:"+e.toString(),Toast.LENGTH_SHORT).show();
}
});
}
private void showData(){
switch (state){
case STATE_NORMAL:
mAdatper = new HotWaresAdapter(datas);
recyclerView.setAdapter(mAdatper);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new WareItemDecoration(getContext(),WareItemDecoration.VERTICAL_LIST));
break;
case STATE_REFREH:
mAdatper.clearData();
mAdatper.addData(datas);
recyclerView.scrollToPosition(0);
layoutRefresh.finishRefresh();
break;
case STATE_MORE:
mAdatper.addData(mAdatper.getDatas().size(),datas);
recyclerView.scrollToPosition(mAdatper.getDatas().size());
layoutRefresh.finishRefreshLoadMore();
break;
}
}
對(duì)于數(shù)據(jù)的請(qǐng)求有三種狀態(tài),分別為 STATE_NORMAL 表示正常狀態(tài)遂庄,STATE_REFREH 表示刷新?tīng)顟B(tài)寥院,STATE_MORE 則表示加載更多的狀態(tài),根據(jù)不同的狀態(tài)下請(qǐng)求數(shù)據(jù)來(lái)執(zhí)行相應(yīng)的操作涛目。
8. 實(shí)現(xiàn)下拉刷新方法
下拉刷新時(shí)秸谢,可以直接調(diào)用獲取數(shù)據(jù)方法 getData(),此時(shí)設(shè)置狀態(tài)為 STATE_REFREH 刷新?tīng)顟B(tài)霹肝。
private void refreshData(){
currPage =1;
state=STATE_REFREH;
getData();
}
9. 實(shí)現(xiàn)加載更多的方法
同樣的估蹄,加載更多其實(shí)就是和下拉刷新?tīng)顟B(tài)有所不同,也是直接調(diào)用獲取數(shù)據(jù)方法 getData()沫换,此時(shí)設(shè)置狀態(tài)為 STATE_MORE 加載更多狀態(tài)臭蚁。
private void loadMoreData(){
currPage = ++currPage;
state = STATE_MORE;
getData();
}
10. 初始化 MaterialRefreshLayout
下拉刷新和加載更多的方法都已經(jīng)實(shí)現(xiàn)好了,可以直接初始化 MaterialRefreshLayout 讯赏,然后擴(kuò)展它的刷新事件監(jiān)聽(tīng)和加載更多事件監(jiān)聽(tīng)垮兑,就可以實(shí)現(xiàn)我們所需要的效果了。
private void initRefreshLayout(){
layoutRefresh.setLoadMore(true);
layoutRefresh.setMaterialRefreshListener(new MaterialRefreshListener() {
@Override
public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
refreshData();
}
@Override
public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
if(currPage <=totalPage)
loadMoreData();
else{
Toast.makeText(getActivity(),"已經(jīng)加載完成漱挎,沒(méi)有更多數(shù)據(jù)了",Toast.LENGTH_SHORT).show();
layoutRefresh.finishRefreshLoadMore();
}
}
});
}
最終效果
所有的都實(shí)現(xiàn)好了之后系枪,運(yùn)行代碼,獲取最終效果磕谅。
[圖片上傳失敗...(image-1189c0-1565145810084)]
最終基本實(shí)現(xiàn)了文章開(kāi)始所要求的可以下拉刷新和加載更多的熱門商品列表的效果嗤无。
關(guān)于 MaterialRefreshLayout 更多的使用,可以參考Github 源碼
【五一大促】菜鳥窩全場(chǎng)android項(xiàng)目實(shí)戰(zhàn)課程低至五折怜庸,更有價(jià)值33元的四款熱門技術(shù)免費(fèi)領(lǐng),17年初優(yōu)惠力度最大的一次活動(dòng)垢村,有意向的童鞋不要錯(cuò)過(guò)
狂戳>>http://www.cniao5.com/hd/2017/51.html