首先写一个工具类:
@GET
Observable get(@Url String url);
网络请求封装:
public final APi aPi;
private OkUtilsRetrofit(){
final Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("http://172.17.8.100/")
.build();
aPi = retrofit.create(APi.class);
}
//暴露
static class UtilsRetrofit{
private static OkUtilsRetrofit okUtilsRetrofit=new OkUtilsRetrofit();
}
public static OkUtilsRetrofit getdanli(){
return UtilsRetrofit.okUtilsRetrofit;
}
MVP框架;
写三个接口:
IModel
void get(String url,Class aClass,NewCallBack newCallBack);
interface NewCallBack{
void onSuccess(Object o);
}
IPresenter
void get(String url, Class aClass);
IMainView
void onSuccess(Object string);
Model层
实现IModel接口
private final OkUtilsRetrofit getdanli;
public Model(){
getdanli = OkUtilsRetrofit.getdanli();
}
@Override
public void get(String url, final Class aClass, final NewCallBack newCallBack) {
getdanli.aPi.get(url)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseBody responseBody) {
Gson gson=new Gson();
try {
final Object o = gson.fromJson(responseBody.string(), aClass);
newCallBack.onSuccess(o);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
Presenter实现IPresenter接口
IMainView iMainView;
private final Model model;
public Presenter(IMainView iMainView) {
this.iMainView = iMainView;
model = new Model();
}
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void get(String url, Class aClass) {
model.get(url,aClass, new IModel.NewCallBack() {
@Override
public void onSuccess(Object o) {
iMainView.onSuccess(o);
}
});
}
Main实现IMainView接口
public class MainActivity extends AppCompatActivity implements IMainView {
@BindView(R.id.xBanner)
XBanner xBanner;
@BindView(R.id.recyclerview)
RecyclerView recyclerview;
private Presenter presenter;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
presenter=new Presenter(this);
presenter.get("small/commodity/v1/bannerShow",BannerBean.class);
}
@Override
public void onSuccess(Object string) {
Toast.makeText(MainActivity.this,""+string,Toast.LENGTH_LONG).show();
if(string instanceof BannerBean)
{
BannerBean banner= (BannerBean) string;
xBanner.setData(banner.getResult(),null);
xBanner.loadImage(new XBanner.XBannerAdapter() {
@Override
public void loadBanner(XBanner banner, Object model, View view, int position) {
BannerBean.ResultBean bean= (BannerBean.ResultBean) model;
Glide.with(MainActivity.this).load(bean.getImageUrl()).into((ImageView) view);
banner.setPageChangeDuration(1000);
}
});
}
}
}