1、Contacts 用来存放所有接口
/**
* 用来存放所有接口
*/
public class Contacts {
//总接口前缀
public static final String BASE_URL = "http://www.zhaoapi.cn/";
//登陆
public static final String USER_LOGIN = "user/login";
//用户信息
public static final String USER_INFO = "user/getUserInfo";
//上传图片
public static final String UP_LOAD_IMAGE = "file/upload";
}
2、ApiService 处理网络接口 GET和POST
/**
* 处理接口 GET和POST
*/
public interface MyApiService {
@GET
Observable<ResponseBody> get(@Url String url, @QueryMap Map<String,String> map);
@POST
Observable<ResponseBody> post(@Url String url, @QueryMap Map<String,String> map);
}
3、Retrofit工具类
public class RetrofitUtils {
private MyApiService myApiService;
private OkHttpClient okHttpClient;
public RetrofitUtils() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient = new OkHttpClient.Builder()
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.connectTimeout(20, TimeUnit.SECONDS)
.addInterceptor(interceptor)
.build();
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(Contrats.BASEURL)
.client(okHttpClient)
.build();
myApiService = retrofit.create(MyApiService.class);
}
public static RetrofitUtils getInstance() {
return RestrofitHolder.retrofitUtils;
}
private static class RestrofitHolder {
private static final RetrofitUtils retrofitUtils = new RetrofitUtils();
}
//GET方式
public void get(String url, Map<String, String> map, final CallBacks callBacks) {
Observer observer = new Observer<ResponseBody>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
if (callBacks != null) {
callBacks.onError(e.getMessage());
}
}
@Override
public void onNext(ResponseBody responseBody) {
if (callBacks != null) {
try {
callBacks.onSuccess(responseBody.string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
myApiService.get(url, map)
.subscribeOn(Schedulers.io()) //io子线程
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
}
//POST方式
public void post(String url, Map<String, String> map, final CallBacks callBacks) {
Observer observer = new Observer<ResponseBody>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
if (callBacks != null) {
callBacks.onError(e.getMessage());
}
}
@Override
public void onNext(ResponseBody responseBody) {
if (callBacks != null) {
try {
callBacks.onSuccess(responseBody.string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
if (map == null) {
map = new HashMap<>();
}
myApiService.post(url, map)
.subscribeOn(Schedulers.io()) //io子线程
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
}
//接口回调
public interface CallBacks {
void onSuccess(String jsonStr);
void onError(String error);
}
}
4、MVP
(1)Model
IModel
public interface IModel {
void getData(String url, Map<String,String> map, Class cla, MyCallBack myCallBack);
void postData(String url, Map<String,String> map, Class cla, MyCallBack myCallBack);
}
MyModel
public class MyModel implements IModel{
@Override
public void getData(String url, Map<String, String> map, final Class cla, final MyCallBack myCallBack) {
RetrofitUtils.getInstance().get(url, map, new RetrofitUtils.CallBacks() {
@Override
public void onSuccess(String jsonStr) {
Gson gson = new Gson();
Object o = gson.fromJson(jsonStr, cla);
myCallBack.success(o);
}
@Override
public void onError(String error) {
}
});
}
@Override
public void postData(String url, Map<String, String> map, final Class cla, final MyCallBack myCallBack) {
RetrofitUtils.getInstance().post(url, map, new RetrofitUtils.CallBacks() {
@Override
public void onSuccess(String jsonStr) {
Gson gson = new Gson();
Object o = gson.fromJson(jsonStr, cla);
myCallBack.success(o);
}
@Override
public void onError(String error) {
}
});
}
}
(2)View
public interface IView<T> {
void success(T success);
void error(T error);
}
(3)Presenter
IPresenter
public interface IPresenter {
void getRequest(String url, Map<String,String> map,Class cla);
void postRequest(String url, Map<String,String> map,Class cla);
}
MyPresenter
public class MyPresenter implements IPresenter {
private MyModel myModel;
private IView iView;
public MyPresenter(IView iView) {
this.iView = iView;
myModel = new MyModel();
}
@Override
public void getRequest(String url,Map<String, String> map,Class cla) {
myModel.getData(url, map, cla, new MyCallBack() {
@Override
public void success(Object successData) {
iView.success(successData);
}
@Override
public void error(Object errorData) {
}
});
}
@Override
public void postRequest(String url, Map<String, String> map,Class cla) {
myModel.postData(url, map, cla, new MyCallBack() {
@Override
public void success(Object successData) {
iView.success(successData);
}
@Override
public void error(Object errorData) {
}
});
}
}
public void onDetch(){
if(myModel != null){
myModel = null;
}
if(iView != null){
iView = null;
}
}
}
5、Adapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<News.DataBean> list;
private Context context;
private int layout;
public MyAdapter(List<News.DataBean> list, Context context,int layout) {
this.list = list;
this.context = context;
this.layout=layout;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i){
View view = LayoutInflater.from(context).inflate(layout, viewGroup, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int i) {
String images = list.get(i).getImages();
String[] splits = images.split("\\|");
Uri parse = Uri.parse(splits[0]);
viewHolder.img.setImageURI(parse);
viewHolder.title.setText(list.get(i).getTitle());
viewHolder.price.setText(list.get(i).getPrice()+"");
//点击
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(callback!=null){
callback.setClick(v,i);
}
}
});
//长按
viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return false;
}
});
/*
//强秀方法
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
News.DataBean dataBean = list.get(i);
EventBus.getDefault().postSticky(dataBean);
context.startActivity(new Intent(context,Main2Activity.class));
}
});
*/
}
@Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private SimpleDraweeView img;
private TextView title;
private TextView price;
public ViewHolder(View itemView) {
super(itemView);
img = itemView.findViewById(R.id.img);
title = itemView.findViewById(R.id.title);
price = itemView.findViewById(R.id.price);
}
}
public interface Callback{
void setClick(View view,int position);
void setLongClick(View view,int position);
}
private Callback callback;
public void setCallback(Callback callback){
this.callback = callback;
}
public void onClick(View v) {
if(callback!=null){
callback.setClick(v, (int) v.getTag());
callback.setLongClick(v, (int) v.getTag());
}
}
}
6、MainActivity
public class MainActivity extends AppCompatActivity implements IView {
@BindView(R.id.headerview)
HeaderView headerview;
@BindView(R.id.xrecy)
XRecyclerView xrecy;
private MyPresenter myPresenter;
private List<News.DataBean> list = new ArrayList<>();
private MyAdapter adapter;
boolean flag=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
Fresco.initialize(this); //Fresco注册
LinearLayoutManager manager = new LinearLayoutManager(this);
xrecy.setLayoutManager(manager);
myPresenter = new MyPresenter(this);
adapter = new MyAdapter(list,this,R.layout.item);
xrecy.setAdapter(adapter);
Map<String,String> map = new HashMap<>();
myPresenter.getRequest(Contacts.URL,map,News.class);
//接口回调
adapter.setCallback(new MyAdapter.Callback() {
@Override
public void setClick(View view, int position) {
News.DataBean dataBean = list.get(position);
EventBus.getDefault().postSticky(dataBean);
startActivity(new Intent(MainActivity.this,Main2Activity.class));
}
@Override
public void setLongClick(View view, int position) {
}
});
//点击图片切换
headerview.getImageView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(flag){
flag=false;
LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this);
xrecy.setLayoutManager(manager);
adapter=new MyAdapter(list,MainActivity.this,R.layout.item);
adapter.notifyDataSetChanged();
}else {
flag=true;
GridLayoutManager manager = new GridLayoutManager(MainActivity.this,2);
xrecy.setLayoutManager(manager);
adapter=new MyAdapter(list,MainActivity.this,R.layout.item2);
adapter.notifyDataSetChanged();
}
}
});
}
//view
@Override
public void success(Object success) {
News news = (News) success;
list.addAll(news.getData());
adapter.notifyDataSetChanged();
}
@Override
public void error(Object error) {
}
@Override
protected void onDestroy() {
super.onDestroy();
if(myPresenter != null){
myPresenter = null;
}
}
}