RecyclerView在现在公司中开发项目使用的还是比较多的,今天我们一起来交流一下RecyclerView多条目.
今天我使用的有:
网络请求框架----->OkHttp二次封装
代码架构------>MVP
图片处理框架----->Fresco
加载多条目------->RecyclerView
接下来开始项目的操作:
1.搭建环境:
配置依赖:
/*android5.0的新特性使用*/
implementation 'com.android.support:support-v13:28.0.0'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:support-v13:28.0.0'
/*OkHttp*/
implementation 'com.squareup.okhttp3:okhttp:3.4.2'
/*RecyclerView*/
implementation 'com.android.support:recyclerview-v7:28.0.0'
/*XRecyclerView*/
implementation 'com.jcodecraeer:xrecyclerview:1.5.9'
/*Fresco的基础依赖*/
implementation 'com.facebook.fresco:fresco:0.14.1'
implementation 'com.google.code.gson:gson:2.8.5'
网络权限:
<uses-permission android:name="android.permission.INTERNET"/>
然后是我们今天加载图片框架使用的是Fresco所以我们需要自定义MyApplication类,那么我们必须在AndroidManifest(清单文件)里注册:
自定义MyAppliaction:
package com.example.myjob.myapp;
import android.app.Application;
import com.facebook.drawee.backends.pipeline.Fresco;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Fresco.initialize(this);
}
}
2.MainActivity:
在这里我们需要进行页面的布局,我这里写了两个fragment,今天主要展示其中RecyclerView多条目的一个页面,首先初始化页面,在这里我采用的是TabLayout和ViewPager来实现页面的联动
package com.example.myjob.activity;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import com.example.myjob.R;
import com.example.myjob.fragment.RecyclerViewFragment;
import com.example.myjob.adapter.ViewPagerAdapter;
import com.example.myjob.fragment.LadderFragment;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ViewPager vp;
private TabLayout tab;
private ViewPagerAdapter mViewPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
initView();
//创建适配器
mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
//创建fragment
ArrayList fragments = new ArrayList<>();
fragments.add(new LadderFragment());
fragments.add(new RecyclerViewFragment());
mViewPagerAdapter.setData(fragments);
vp.setAdapter(mViewPagerAdapter);
tab.setupWithViewPager(vp);
}
private void initView() {
vp = (ViewPager) findViewById(R.id.vp);
tab = (TabLayout) findViewById(R.id.tab);
}
}
布局文件:
ViewPager+TabLayout的适配器
package com.example.myjob.adapter;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
public class ViewPagerAdapter extends FragmentPagerAdapter {
private ArrayList mFragments;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
mFragments = new ArrayList<>();
}
public void setData(ArrayList fragments) {
this.mFragments = fragments;
}
@Override
public Fragment getItem(int i) {
return mFragments.get(i);
}
@Override
public int getCount() {
return mFragments.size();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "三色阶梯";
case 1:
return "主页";
}
return null;
}
}
2,Recycler多条目展示页面
package com.example.myjob.fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.myjob.R;
import com.example.myjob.adapter.RecyclerViewAdapter;
import com.example.myjob.bean.DataItem;
import com.example.myjob.persenter.RecyclerViewPersenter;
import com.example.myjob.view.RecyclerViewView;
import java.util.List;
/**
* date:2018/12/1
* author:李壮(大壮)
* function:
*/
public class RecyclerViewFragment extends Fragment implements RecyclerViewView {
private RecyclerView recyclerview;
private RecyclerViewAdapter mRecyclerViewAdapter;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = View.inflate(getActivity(), R.layout.recyclerview, null);
//初始化控件
initView(view);
//创建适配器
mRecyclerViewAdapter = new RecyclerViewAdapter(getActivity());
//加载数据
initData();
//添加到适配器
recyclerview.setAdapter(mRecyclerViewAdapter);
//设置布局管理器
recyclerview.setLayoutManager(new LinearLayoutManager(getContext(),OrientationHelper.VERTICAL,false));
return view;
}
//获取网络数据
private void initData() {
//创建P层
new RecyclerViewPersenter().onCreat(this).loadData();
}
private void initView(View view) {
recyclerview = (RecyclerView) view.findViewById(R.id.recyclerview);
}
@Override
public void success(final List data) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
mRecyclerViewAdapter.setData(data);
}
});
}
@Override
public void failtrue() {
}
}
P层
package com.example.myjob.persenter;
import com.example.myjob.bean.DataItem;
import com.example.myjob.model.RecyclerViewModel;
import com.example.myjob.util.OkHttpUtils;
import com.example.myjob.view.RecyclerViewView;
import java.util.List;
public class RecyclerViewPersenter {
private RecyclerViewView mRecyclerViewView;
public RecyclerViewPersenter onCreat(RecyclerViewView recyclerViewView) {
mRecyclerViewView = recyclerViewView;
return this;
}
//初始化网络
public void loadData(){
//创建M层
new RecyclerViewModel().doGet(OkHttpUtils.getInstance(), new RecyclerViewModel.Callback() {
@Override
public void success(List<DataItem.ResultBean.DataBean> data) {
mRecyclerViewView.success(data);
}
@Override
public void failtrue(Exception e) {
}
});
}
}
M层
package com.example.myjob.model;
import com.example.myjob.bean.DataItem;
import com.example.myjob.util.OkHttpUtils;
import com.google.gson.Gson;
import java.util.List;
/**
* date:2018/12/1
* author:李壮(大壮)
* function:
*/
public class RecyclerViewModel {
private String path = "http://v.juhe.cn/toutiao/index?type=&key=83a69c67e9272f816e42450ef0eb50ee";
public void doGet(OkHttpUtils okHttpUtils, final Callback callback){
OkHttpUtils.getInstance().doGet(path, new OkHttpUtils.onOkCallback() {
@Override
public void success(String json) {
DataItem dataItem = new Gson().fromJson(json, DataItem.class);
List data = dataItem.getResult().getData();
callback.success(data);
}
@Override
public void failtrue(Exception e) {
callback.failtrue(e);
}
});
}
public interface Callback{
void success(List data);
void failtrue(Exception e);
}
}
V层
package com.example.myjob.view;
import com.example.myjob.bean.DataItem;
import java.util.List;
public interface RecyclerViewView {
void success(List<DataItem.ResultBean.DataBean> data);
void failtrue();
}
RecyclerView多条目适配器
package com.example.myjob.adapter;
import android.content.Context;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.myjob.R;
import com.example.myjob.bean.DataItem;
import com.facebook.drawee.view.SimpleDraweeView;
import java.util.ArrayList;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter {
private final int TYPEONE = 1;
private final int TYPETWO = 2;
private final int TYPETHREE = 3;
private Context mContext;
private List mDataBeans;
public RecyclerViewAdapter(Context context) {
this.mContext = context;
mDataBeans = new ArrayList<>();
}
public void setData(List data) {
mDataBeans.clear();
if (data != null){
mDataBeans.addAll(data);
}
notifyDataSetChanged();
}
@Override
public int getItemViewType(int position) {
if (mDataBeans.get(position).getThumbnail_pic_s03() != null){
return TYPETHREE;
}else if (mDataBeans.get(position).getThumbnail_pic_s02() != null){
return TYPETWO;
}else {
return TYPEONE;
}
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
if (i == TYPEONE){
View view = View.inflate(mContext,R.layout.one_item,null);
ViewHolderOne viewHolderOne = new ViewHolderOne(view);
return viewHolderOne;
}else if (i == TYPETWO){
View view = View.inflate(mContext,R.layout.two_item,null);
ViewHolderTwo viewHolderTwo = new ViewHolderTwo(view);
return viewHolderTwo;
}else if (i == TYPETHREE){
View view = View.inflate(mContext,R.layout.three_item,null);
ViewHolderThree viewHolderThree = new ViewHolderThree(view);
return viewHolderThree;
}
return null;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
int type = viewHolder.getItemViewType();
if (type == TYPEONE){
ViewHolderOne viewHolderOne = (ViewHolderOne)viewHolder;
Uri parse = Uri.parse(mDataBeans.get(i).getThumbnail_pic_s());
//GenericDraweeHierarchyBuilder genericDraweeHierarchyBuilder = new GenericDraweeHierarchyBuilder(mContext.getResources());
//viewHolderOne.recyclerview_one_icon.setHierarchy(genericDraweeHierarchyBuilder);
viewHolderOne.recyclerview_one_icon.setImageURI(parse);
viewHolderOne.recyclerview_one_title.setText(mDataBeans.get(i).getTitle());
return;
}else if (type == TYPETWO){
ViewHolderTwo viewHolderTwo = (ViewHolderTwo) viewHolder;
Uri parseLeft = Uri.parse(mDataBeans.get(i).getThumbnail_pic_s());
Uri parseRight = Uri.parse(mDataBeans.get(i).getThumbnail_pic_s02());
// GenericDraweeHierarchyBuilder genericDraweeHierarchyBuilder = new GenericDraweeHierarchyBuilder(mContext.getResources());
viewHolderTwo.recyclertwo_two_left_icon.setImageURI(parseLeft);
viewHolderTwo.recyclertwo_two_right_icon.setImageURI(parseRight);
return;
}else{
ViewHolderThree viewHolderThree = (ViewHolderThree) viewHolder;
Uri parseLeft = Uri.parse(mDataBeans.get(i).getThumbnail_pic_s());
Uri parseCenter = Uri.parse(mDataBeans.get(i).getThumbnail_pic_s02());
Uri parseRight = Uri.parse(mDataBeans.get(i).getThumbnail_pic_s03());
viewHolderThree.recyclerview_three_left_icon.setImageURI(parseLeft);
viewHolderThree.recyclerview_three_center_icon.setImageURI(parseCenter);
viewHolderThree.recyclerview_three_right_icon.setImageURI(parseRight);
return;
}
}
@Override
public int getItemCount() {
return mDataBeans.size();
}
private class ViewHolderOne extends RecyclerView.ViewHolder{
private SimpleDraweeView recyclerview_one_icon;
private TextView recyclerview_one_title;
public ViewHolderOne(@NonNull View itemView) {
super(itemView);
recyclerview_one_icon = itemView.findViewById(R.id.recyclerview_one_icon);
recyclerview_one_title = itemView.findViewById(R.id.recyclerview_one_title);
}
}
private class ViewHolderTwo extends RecyclerView.ViewHolder {
private SimpleDraweeView recyclertwo_two_left_icon;
private SimpleDraweeView recyclertwo_two_right_icon;
public ViewHolderTwo(@NonNull View itemView) {
super(itemView);
recyclertwo_two_left_icon = itemView.findViewById(R.id.recyclerview_two_left_icon);
recyclertwo_two_right_icon = itemView.findViewById(R.id.recyclerview_two_right_icon);
}
}
private class ViewHolderThree extends RecyclerView.ViewHolder{
private SimpleDraweeView recyclerview_three_left_icon;
private SimpleDraweeView recyclerview_three_center_icon;
private SimpleDraweeView recyclerview_three_right_icon;
public ViewHolderThree(@NonNull View itemView) {
super(itemView);
recyclerview_three_left_icon = itemView.findViewById(R.id.recyclerview_three_left_icon);
recyclerview_three_center_icon = itemView.findViewById(R.id.recyclerview_three_center_icon);
recyclerview_three_right_icon = itemView.findViewById(R.id.recyclerview_three_right_icon);
}
}
}
3.OkHttp二次封装:
package com.example.myjob.util;
import android.os.Handler;
import android.os.Looper;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* date:2018/12/1
* author:李壮(大壮)
* function:
*/
public class OkHttpUtils {
private static OkHttpUtils mOkHttpUtils;
private Handler mHandler;
private OkHttpClient mOkHttpClient;
//创建一个私有的构造参数
private OkHttpUtils(){
//创建一个主线程handler
mHandler = new Handler(Looper.getMainLooper());
mOkHttpClient = new OkHttpClient.Builder()
.readTimeout(10,TimeUnit.SECONDS)
.connectTimeout(10,TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.build();
}
//单例模式
public static OkHttpUtils getInstance(){
if (mOkHttpUtils == null){
synchronized (OkHttpUtils.class){
if (mOkHttpUtils == null){
mOkHttpUtils = new OkHttpUtils();
}
}
}
return mOkHttpUtils;
}
//接口回调
public interface onOkCallback{
//成功
void success(String json);
//失败
void failtrue(Exception e);
}
//封装doPost
public void doPost(String url, Map<String,String> map, final onOkCallback okCallback){
FormBody.Builder builder = new FormBody.Builder();
if (map != null){
for (String key : map.keySet()){
builder.add(key,map.get(key));
}
}
FormBody formBody = builder.build();
//创建Request
final Request request = new Request.Builder()
.post(formBody)
.url(url)
.build();
//创建call
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
if (okCallback != null){
mHandler.post(new Runnable() {
@Override
public void run() {
okCallback.failtrue(e);
}
});
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
if (response != null && response.isSuccessful()){
final String json = response.body().string();
if (okCallback != null){
mHandler.post(new Runnable() {
@Override
public void run() {
okCallback.success(json);
}
});
}
}
}catch (Exception e){
e.printStackTrace();
}
}
});
}
//封装doGet
public void doGet(String url, final onOkCallback okCallback){
//创建Request
final Request request = new Request.Builder()
.get()
.url(url)
.build();
//创建call
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
if (okCallback != null){
mHandler.post(new Runnable() {
@Override
public void run() {
okCallback.failtrue(e);
}
});
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
if (response != null && response.isSuccessful()){
final String json = response.body().string();
if (okCallback != null){
mHandler.post(new Runnable() {
@Override
public void run() {
okCallback.success(json);
}
});
}
}
}catch (Exception e){
e.printStackTrace();
}
}
});
}
}
4.Bean类:
package com.example.myjob.bean;
import java.util.List;
/**
* date:2018/12/1
* author:李壮(大壮)
* function: 多条目展示bean类
*/
public class DataItem {
private String reason;
private ResultBean result;
private int error_code;
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public ResultBean getResult() {
return result;
}
public void setResult(ResultBean result) {
this.result = result;
}
public int getError_code() {
return error_code;
}
public void setError_code(int error_code) {
this.error_code = error_code;
}
public static class ResultBean {
private String stat;
private List data;
public String getStat() {
return stat;
}
public void setStat(String stat) {
this.stat = stat;
}
public List getData() {
return data;
}
public void setData(List data) {
this.data = data;
}
public static class DataBean {
private String uniquekey;
private String title;
private String date;
private String category;
private String author_name;
private String url;
private String thumbnail_pic_s;
private String thumbnail_pic_s02;
private String thumbnail_pic_s03;
public String getUniquekey() {
return uniquekey;
}
public void setUniquekey(String uniquekey) {
this.uniquekey = uniquekey;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getAuthor_name() {
return author_name;
}
public void setAuthor_name(String author_name) {
this.author_name = author_name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getThumbnail_pic_s() {
return thumbnail_pic_s;
}
public void setThumbnail_pic_s(String thumbnail_pic_s) {
this.thumbnail_pic_s = thumbnail_pic_s;
}
public String getThumbnail_pic_s02() {
return thumbnail_pic_s02;
}
public void setThumbnail_pic_s02(String thumbnail_pic_s02) {
this.thumbnail_pic_s02 = thumbnail_pic_s02;
}
public String getThumbnail_pic_s03() {
return thumbnail_pic_s03;
}
public void setThumbnail_pic_s03(String thumbnail_pic_s03) {
this.thumbnail_pic_s03 = thumbnail_pic_s03;
}
}
}
}
最后还有一些布局:RecyclerView的布局,多条目的布局:
recyclerView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
三种布局Xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/recyclerview_one_icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="@mipmap/ic_launcher"/>
<TextView
android:id="@+id/recyclerview_one_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="标题"/>
</LinearLayout>
<?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">
<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/recyclerview_two_right_icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginTop="25dp"
android:layout_marginEnd="108dp"
android:layout_marginRight="108dp"
android:src="@mipmap/ic_launcher" />
<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/recyclerview_two_left_icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginTop="21dp"
android:layout_marginEnd="238dp"
android:layout_marginRight="238dp"
android:src="@mipmap/ic_launcher" />
</RelativeLayout>
<?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">
<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/recyclerview_three_left_icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="@mipmap/ic_launcher"/>
<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/recyclerview_three_center_icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="163dp"
android:layout_marginLeft="163dp"
android:layout_marginTop="0dp"
android:src="@mipmap/ic_launcher" />
<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/recyclerview_three_right_icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="0dp"
android:src="@mipmap/ic_launcher" />
</RelativeLayout>
搞定