本文為菜鳥窩作者 吳威龍 投稿
菜鳥窩是專業(yè)的程序猿在線學(xué)習(xí)平臺(tái),提供最系統(tǒng)的 Android 項(xiàng)目實(shí)戰(zhàn)課程
如需轉(zhuǎn)載,請(qǐng)聯(lián)系菜鳥窩公眾號(hào)(cniao5),并注明出處。
前言
幾個(gè)月前寫了篇使用 RecyclerView 的簡(jiǎn)單介紹:【Android 基礎(chǔ)】RecyclerView 概述以及使用步驟
現(xiàn)在結(jié)合 ButterKnife+Retrofit+Picasso+RecycleView 實(shí)現(xiàn)一個(gè)小案例。關(guān)于 Retrofit、Picasso、ButterKnife 的詳細(xì)使用請(qǐng)看我之前寫的文章
【Android 進(jìn)階】Retrofit2 目前最優(yōu)雅的網(wǎng)絡(luò)請(qǐng)求框架
build.gradle 文件
apply plugin: 'android-apt'
.
.
.
//butterknife
compile 'com.jakewharton:butterknife:8.4.0'
apt 'com.jakewharton:butterknife-compiler:8.4.0'
//retrofit
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
// okHttp
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
//picasso
compile 'com.squareup.picasso:picasso:2.5.2'
數(shù)據(jù)接口
// Callback 類型為自定義的 javaBean
public interface ApiService {
public static final String BASE_URL = "http://112.xxx.22.238:8081/course_api/xxxplay/";
@GET("featured")
public Call<PageBean<AppInfo>> getApps(@Query("p") String jsonParam);
}
Http 幫助類
public class HttpManager {
public OkHttpClient getOkHttpClient(){
// log用攔截器
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// 開發(fā)模式記錄整個(gè)body,否則只記錄基本信息如返回200,http協(xié)議版本等
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
// 如果使用到HTTPS,我們需要?jiǎng)?chuàng)建SSLSocketFactory,并設(shè)置到client
// SSLSocketFactory sslSocketFactory = null;
return new OkHttpClient.Builder()
// HeadInterceptor實(shí)現(xiàn)了Interceptor,用來往Request Header添加一些業(yè)務(wù)相關(guān)數(shù)據(jù),如APP版本,token信息
// .addInterceptor(new HeadInterceptor())
.addInterceptor(logging)
// 連接超時(shí)時(shí)間設(shè)置
.connectTimeout(10, TimeUnit.SECONDS)
// 讀取超時(shí)時(shí)間設(shè)置
.readTimeout(10, TimeUnit.SECONDS)
.build();
}
public Retrofit getRetrofit(OkHttpClient okHttpClient){
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(ApiService.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(okHttpClient);
return builder.build();
}
}
RecyclerView 中每個(gè) item 的布局文件
單個(gè) item 的布局樣式如下,具體的 layout 文件就不貼出來了,放在 adapter 里面加載的。

RecyclerView 的 Adatper
使用過 Listview 和 RecyclerView 的同學(xué)都知道,除了上一點(diǎn)說到的每個(gè) item 的布局外,還需要給 Listview 或 RecyclerView 寫一個(gè)適配器,這適配器的寫法也是有跡可循的,多寫幾次也就不陌生了
不懂 RecyclerView 的 Adatper 怎么寫的請(qǐng)看下面代碼中的注釋哈,應(yīng)該交代的挺清楚的。
下面示例 adapter 里面就使用了 Picasso 加載圖片,使用 ButterKnife 綁定 view 省卻了 FindViewById 的繁瑣。
public class RecomendAppAdatper extends RecyclerView.Adapter<RecomendAppAdatper.ViewHolder> {
private Context mContext;
private List<AppInfo> mDatas;
// 通過構(gòu)造器傳進(jìn)來的數(shù)據(jù)
private LayoutInflater mLayoutInflater;
public RecomendAppAdatper(Context context, List<AppInfo> datas) {
this.mDatas = datas;
this.mContext = context;
mLayoutInflater = LayoutInflater.from(context);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(mLayoutInflater.inflate(R.layout.template_recomend_app, parent, false));
//指定 viewHolder 的布局樣式,并返回該 viewHolder
}
// 綁定數(shù)據(jù),就是給控件設(shè)置值
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
AppInfo appInfo = mDatas.get(position);
// holder.mImgIcon
String baseImgUrl ="http://file.market.xiaomi.com/mfc/thumbnail/png/w150q80/";
Picasso.with(mContext).load(baseImgUrl +appInfo.getIcon()).into(holder.mImgIcon);
holder.mTextTitle.setText(appInfo.getDisplayName());
holder.mTextSize.setText((appInfo.getApkSize() / 1024 /1024) +" MB");
}
@Override
public int getItemCount() {
return mDatas.size();
}
//onCreateViewHolder 指定 viewHolder 的布局樣式之后,使用 ButterKnife 進(jìn)行控件綁定
public class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.img_icon)
ImageView mImgIcon;
@BindView(R.id.text_title)
TextView mTextTitle;
@BindView(R.id.text_size)
TextView mTextSize;
@BindView(R.id.btn_dl)
Button mBtnDl;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
在 Fragment 中使用 RecyclerView
/**
* 通過 Retrofit 獲取數(shù)據(jù) datas ,再把數(shù)據(jù)丟給 adapter
*/
public class RecommendFragment extends Fragment implements RecommendContract.View {
@BindView(R.id.recycle_view)
RecyclerView mRecyclerView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recomend, container, false);
ButterKnife.bind(this, view);
initData();
return view;
}
private void initData(){
HttpManager manager = new HttpManager();
ApiService apiService = manager.getRetrofit(manager.getOkhttpClient()).create(ApiService.class);
apiService.getApps("{'page':'0'}").enqueue(new Callback<PageBean<AppInfo>> response){
@Override
public void onResponse(Call<PageBean<AppInfo>> call, Response<PageBean<AppInfo>> response){
<PageBean<AppInfo>> pageBean = response.body();
List<AppInfo> datas = pageBean.getDatas();
//把網(wǎng)絡(luò)請(qǐng)求獲得的數(shù)據(jù)出去,準(zhǔn)備給 Adatper 使用
initRecycleView(datas);
}
@Override
public void onFailure(Call<PageBean<AppInfo>> call, Throwable t){
}
});
}
private void initRecycleView(List<AppInfo> datas){
//為 RecyclerView 設(shè)置布局管理器
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//為 RecyclerView 設(shè)置分割線(這個(gè)可以對(duì) DividerItemDecoration 進(jìn)行修改,自定義)
mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.HORIZONTAL_LIST));
//動(dòng)畫
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mAdatper = new RecomendAppAdatper(getActivity(),datas);
mRecyclerView.setAdapter(mAdatper);
}
.
.
.
}
成果如下

總結(jié)
這個(gè)案例的難點(diǎn)主要是 adapter 類的編寫,其他比如 ButterKnife、Retrofit、Picasso 都是知道怎么使用即可。
擼這個(gè)項(xiàng)目的一半,你就是大神 , 戳http://mp.weixin.qq.com/s/ZagocTlDfxZpC2IjUSFhHg