Android简单使用retrofit实现左右联动

效果图

Android简单使用retrofit实现左右联动_第1张图片

所需依赖

依赖较多

implementation ‘com.jakewharton:butterknife:10.2.1’//Butterknife配置
annotationProcessor ‘com.jakewharton:butterknife-compiler:10.2.1’//Butterknife注解处理器
implementation ‘com.github.bumptech.glide:glide:4.10.0’//图片加载框架

implementation 'androidx.recyclerview:recyclerview:1.1.0'//recycerview


implementation 'org.greenrobot:eventbus:3.1.1' //eventbus 事件总线,传值
//retrofit核心库
implementation 'com.squareup.retrofit2:retrofit:2.6.2'

//retrofit辅助,gson解析的库
implementation 'com.squareup.retrofit2:converter-gson:2.6.2'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.6.2' // 必要依赖,和Rxjava结合必须用到,下面会提到
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'//切换到主线程的依赖

//okhttp日志拦截器
implementation 'com.squareup.okhttp3:logging-interceptor:4.2.2'

首先先创建左右侧的Entity

创建ApiService接口

public interface ApiService {
@GET(“左侧尾部地址”)
Observable < LeftEntity > getResult();
//Observable导io包,左侧Entity的名称及获取的集合名称
@GET(“右侧尾部地址”)
Observable< RightEntity > getRight(@QueryMap HashMap params);
//右侧Entity的名称及获取的集合名称(获取map,创建Hasmap)
}

创建RetrofitUtils工具类

public class RetroitUtils {
private static RetroitUtils retroit;
private final Retrofit retrofit;

public RetroitUtils() {
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .build();

    retrofit = new Retrofit.Builder()
            .baseUrl("左右侧前段相同地址")
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();
}

public static RetroitUtils getInstance() {
    if (retroit==null){
        synchronized (RetroitUtils.class){
            if (retroit==null){
                retroit=new RetroitUtils();
            }
        }
    }
    return retroit;
}

public T createservice(Class tClass){
    T t = retrofit.create(tClass);
    return t;
}

}

创建MVP的conntract契约接口

public interface INewsConntract {
interface IModel extends BaseModel{
interface ModelCallBack{
void success(Object obj);
void failure(Throwable throwable);
}
void getLeft(ModelCallBack modelCallBack);
void getRight(HashMap params,ModelCallBack modelCallBack);
}
interface IView{
void success(Object obj);
void failure(Throwable throwable);
}
interface IPresenter{
void getLeft();
void getRight(HashMap params);
}
}

创建MVP的M层

需要继承契约类对应的接口

public class Model implements INewsConntract.IModel {

@Override
public void getLeft(ModelCallBack modelCallBack) {
    RetroitUtils.getInstance().createservice(ApiService.class)//创建服务
            .getResult()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(LeftEntity leftEntity) {
                    modelCallBack.success(leftEntity);
                }

                @Override
                public void onError(Throwable e) {
                    modelCallBack.failure(e);
                }

                @Override
                public void onComplete() {

                }
            });
}

@Override
public void getRight(HashMap params, ModelCallBack modelCallBack) {
    RetroitUtils.getInstance().createservice(ApiService.class)
            .getRight(params)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(RightEntity rightEntity) {
                    modelCallBack.success(rightEntity);
                }

                @Override
                public void onError(Throwable e) {
                    modelCallBack.failure(e);

                }

                @Override
                public void onComplete() {

                }
            });

}

}

创建MVP的P层

需要继承契约类对应的接口

public class Presenter implements INewsConntract.IPresenter {
private INewsConntract.IView iView;
private Model model;

public Presenter(INewsConntract.IView iView) {
    this.iView = iView;
    this.model = new Model();
}

@Override
public void getLeft() {
    model.getLeft(new INewsConntract.IModel.ModelCallBack() {
        @Override
        public void success(Object obj) {
            iView.success(obj);
        }

        @Override
        public void failure(Throwable throwable) {
            iView.failure(throwable);
        }
    });

}

@Override
public void getRight(HashMap params) {

    model.getRight(params, new INewsConntract.IModel.ModelCallBack() {
        @Override
        public void success(Object obj) {
            iView.success(obj);
        }

        @Override
        public void failure(Throwable throwable) {
            iView.failure(throwable);
        }
    });
}

}

显示界面xml设置



显示层的Activity

#### 需要继承契约类对应的view层接口,这里用到了ButterKnife及EventBus

public class MainActivity extends AppCompatActivity implements INewsConntract.IView {

@BindView(R.id.rv_left)
RecyclerView rvLeft;
@BindView(R.id.rv_right)
RecyclerView rvRight;
private Presenter presenter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    presenter = new Presenter(this);
    ButterKnife.bind(this);
    EventBus.getDefault().register(this);
    rvLeft.setLayoutManager(new LinearLayoutManager(this));
    rvRight.setLayoutManager(new GridLayoutManager(this,2));
    if (RetroitUtils.getInstance().isNet()){
        presenter.getLeft();
    }
}

@Override
public void success(Object obj) {
    if (obj instanceof LeftEntity){

        List secondCategoryVo = ((LeftEntity) obj).getResult().get(0).getSecondCategoryVo();
        LeftAdapter leftAdapter = new LeftAdapter(this, secondCategoryVo);
        rvLeft.setAdapter(leftAdapter);

        leftAdapter.setLeftClick(new LeftAdapter.LeftClick() {
            @Override
            public void leftItemClick(String id) {
                EventBus.getDefault().post(id);
            }
        });

    }else if (obj instanceof RightEntity){
        List result = ((RightEntity) obj).result;
        RightAdapter rightAdapter = new RightAdapter(this,result);
        rvRight.setAdapter(rightAdapter);
    }
}

@Override
public void failure(Throwable throwable) {

}

@Subscribe(threadMode = ThreadMode.MAIN)
public void getId(String id){
    HashMap params = new HashMap<>();
    params.put("categoryId",id);
    params.put("page","1");
    params.put("count","10");
    presenter.getRight(params);
}

}

左侧的适配器配置

public class LeftAdapter extends RecyclerView.Adapter {

private final Context context;
private final List secondCategoryVo;

public LeftAdapter(Context context, List secondCategoryVo) {

    this.context = context;
    this.secondCategoryVo = secondCategoryVo;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View inflate = View.inflate(context, R.layout.item, null);
    MyViewHolder myViewHolder = new MyViewHolder(inflate);
    return myViewHolder;
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
    holder.tv.setText(secondCategoryVo.get(position).getName());
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            leftClick.leftItemClick(secondCategoryVo.get(position).getId());
        }
    });
}

@Override
public int getItemCount() {
    return secondCategoryVo.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    @BindView(R.id.tv)
    TextView tv;
    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
    }
}
private LeftClick leftClick;

public void setLeftClick(LeftClick leftClick) {
    this.leftClick = leftClick;
}

public interface LeftClick{
    void leftItemClick(String id);
}

}

右侧的适配器配置

public class RightAdapter extends RecyclerView.Adapter {
private final Context context;
private final List result;

public RightAdapter(Context context, List result) {
    this.context = context;
    this.result = result;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = View.inflate(context, R.layout.right_item, null);
    MyViewHolder myViewHolder = new MyViewHolder(view);
    return myViewHolder;
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
    holder.tv.setText(result.get(position).commodityName);

    Glide.with(context).load(result.get(position).masterPic)
            .placeholder(R.mipmap.ic_launcher)
            .error(R.mipmap.ic_launcher)
            .into(holder.iv);
}

@Override
public int getItemCount() {
    return result.size();
}

class MyViewHolder extends RecyclerView.ViewHolder {

    @BindView(R.id.iv)
    ImageView iv;
    @BindView(R.id.tv)
    TextView tv;
    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        ButterKnife.bind(this,itemView);
    }
}

}

仅仅简单的实现,适合初学者参考学习

你可能感兴趣的:(retrofit使用,butterknife使用)