mvp框架和上拉下拉展示
作者:互联网
1.框架分层
2.interfaces接口
package com.example.denglu.view.interfaces;
public interface IMainView<T> extends IBaseView {
void onSuccess(T t);
void onErr(String errMsg);
}
3.okhttp封装
package com.example.denglu.model.util;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class HttpUtils<T> {
private final OkHttpClient okHttpClient;
private HttpUtils(){
okHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new LoginIntecepter())
.readTimeout(5,TimeUnit.SECONDS)
.writeTimeout(5,TimeUnit.SECONDS)
.build();
}
public static HttpUtils getHttpUtilsInstance(){
return HttpUtilsInstance.httpUtils;
}
private static class HttpUtilsInstance{
private static HttpUtils httpUtils=new HttpUtils();
}
private class LoginIntecepter implements Interceptor{
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RequestBody body = request.body();
Headers headers = request.headers();
Response response = chain.proceed(request);
Headers headers1 = request.headers();
return response;
}
}
@SuppressLint("HandlerLeak")
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what==0){
T t =(T) msg.obj;
mCallback.onResponse(t);
}else{
String err =(String) msg.obj;
mCallback.onFail(err);
}
}
};
private CallBackData mCallback;
public void getData(String url,final Class<T> tClass,final CallBackData callBackData){
this.mCallback=callBackData;
Request request = new Request.Builder()
.url(url)
.get()
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Message message = handler.obtainMessage();
message.what=-1;
message.obj=e.getMessage();
handler.sendMessage(message);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String string = response.body().string();
Gson gson=new Gson();
T t = gson.fromJson(string, tClass);
Message message = handler.obtainMessage();
message.obj=t;
message.what=0;
handler.sendMessage(message);
}
});
}
public void postData(String url, final Class<T> tClass, HashMap<String,String> hashMap, final CallBackData callBackData){
this.mCallback=callBackData;
FormBody.Builder builder = new FormBody.Builder();
for (Map.Entry<String,String> stringStringEntry:hashMap.entrySet()){
String key = stringStringEntry.getKey();
String value = stringStringEntry.getValue();
builder.add(key,value);
}
FormBody formBody = builder.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Call call=okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Message message = handler.obtainMessage();
message.obj=e.getMessage();
message.what=-1;
handler.sendMessage(message);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String string = response.body().string();
Gson gson=new Gson();
T t = gson.fromJson(string, tClass);
Message message = handler.obtainMessage();
message.what=0;
message.obj=t;
handler.sendMessage(message);
}
});
}
public interface CallBackData<D>{
public void onResponse(D d);
public void onFail(String err);
}
}
4.basepresenter
package com.example.denglu.presenter;
import com.example.denglu.view.interfaces.IBaseView;
public class BasePresenter<V> implements IBaseView {
private V view;
public void setView(V view) {
this.view = view;
}
public V getView() {
return view;
}
public void detachView(){
this.view=null;
}
}
5.Mainpresenter
package com.example.denglu.presenter;
import android.util.Log;
import com.example.denglu.constant.Constant;
import com.example.denglu.model.bean.LoginBean;
import com.example.denglu.model.bean.NewsBean;
import com.example.denglu.model.util.HttpUtils;
import com.example.denglu.view.interfaces.IMainView;
import java.util.HashMap;
public class MainPresenter extends BasePresenter<IMainView>{
private final HttpUtils httpUtilsInstance;
public MainPresenter(){
httpUtilsInstance = HttpUtils.getHttpUtilsInstance();
}
public void postData(String url, HashMap<String, String> map){
HttpUtils.getHttpUtilsInstance().postData(url, LoginBean.class, map, new HttpUtils.CallBackData<LoginBean>() {
@Override
public void onResponse(LoginBean d) {
if (d!=null){
getView().onSuccess(d);
}
}
@Override
public void onFail(String err) {
getView().onErr(err);
}
});
}
public void loadDataFromNer(int page){
httpUtilsInstance.getData(Constant.BASE_URL+page,NewsBean.class, new HttpUtils.CallBackData<NewsBean>() {
@Override
public void onResponse(NewsBean newsBean) {
if (getView()!=null){
getView().onSuccess(newsBean);
}else{
Log.e("myMessage","没有绑定");
}
}
@Override
public void onFail(String err) {
getView().onErr(err);
}
});
}
}
6activity
package com.example.denglu.view.activity;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ProgressBar;
import com.example.denglu.R;
import com.example.denglu.model.bean.NewsBean;
import com.example.denglu.presenter.MainPresenter;
import com.example.denglu.view.adapter.NewsAdapter;
import com.example.denglu.view.interfaces.IMainView;
public class MainActivity extends BaseActivity implements IMainView<NewsBean>,SwipeRefreshLayout.OnRefreshListener {
private RecyclerView recyclerView;
private SwipeRefreshLayout swipeRefreshLayout;
private LinearLayoutManager linearLayoutManager;
private NewsAdapter newsAdapter;
private MainPresenter mainPresenter;
private int page=1;
private ProgressBar progressBar;
@Override
protected int setLayout() {
return R.layout.activity_main;
}
@Override
protected void initView() {
recyclerView = findViewById(R.id.recyclerView);
swipeRefreshLayout = findViewById(R.id.swiperefresh);
swipeRefreshLayout.setOnRefreshListener(this);
progressBar = findViewById(R.id.progeress);
}
@Override
protected void initData() {
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.addItemDecoration(new DividerItemDecoration(this,LinearLayoutManager.VERTICAL));
recyclerView.setLayoutManager(linearLayoutManager);
newsAdapter = new NewsAdapter(this);
recyclerView.setAdapter(newsAdapter);
mainPresenter = new MainPresenter();
mainPresenter.setView(this);
mainPresenter.loadDataFromNer(page);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int childCount = linearLayoutManager.getChildCount();
int itemCount = linearLayoutManager.getItemCount();
int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
if (childCount+firstVisibleItemPosition>=itemCount){
if (progressBar.getVisibility()!=View.VISIBLE){
loadMore();
}
}
}
});
}
@Override
public void onSuccess(NewsBean newsBean) {
progressBar.setVisibility(View.GONE);
newsAdapter.setData(newsBean.getResults(),isRefreshing);
}
@Override
public void onErr(String errMsg) {
progressBar.setVisibility(View.GONE);
}
@Override
protected void onDestroy() {
super.onDestroy();
mainPresenter.detachView();
}
private boolean isRefreshing;
@Override
public void onRefresh() {
isRefreshing=true;
page=1;
mainPresenter.loadDataFromNer(page);
swipeRefreshLayout.setRefreshing(false);
}
private void loadMore() {
isRefreshing=false;
page++;
mainPresenter.loadDataFromNer(page);
}
}
7.adapter
package com.example.denglu.view.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.denglu.R;
import com.example.denglu.model.bean.NewsBean;
import com.example.denglu.view.activity.MainActivity;
import java.util.ArrayList;
import java.util.List;
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.MyViewHolder> {
private Context mContext;
private ArrayList<NewsBean.ResultsBean> mList=new ArrayList<>();
public NewsAdapter(Context context) {
this.mContext=context;
}
public void setData(List<NewsBean.ResultsBean> list, boolean isRefreshing){
if (list!=null){
if (isRefreshing){
mList.clear();
}
mList.addAll(list);
notifyDataSetChanged();
}
}
@NonNull
@Override
public NewsAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view=LayoutInflater.from(mContext).inflate(R.layout.itme,null);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
@Override
public void onBindViewHolder(@NonNull NewsAdapter.MyViewHolder myViewHolder, int i) {
if (mList.get(i)!=null){
myViewHolder.name.setText(i+" "+mList.get(i).getTitle()+" ");
}
}
@Override
public int getItemCount() {
return mList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
}
}
}
8布局
<?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"
android:orientation="vertical">
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swiperefresh"
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>
</android.support.v4.widget.SwipeRefreshLayout>
<ProgressBar
android:id="@+id/progeress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Large"
android:layout_centerHorizontal="true"
android:visibility="gone"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
9创建接口类
package com.example.denglu.constant;
public class Constant {
public static final String BASE_URL = " http://gank.io/api/xiandu/data/id/appinn/count/10/page/";
}
标签:mvp,展示,void,上拉下,example,Override,import,com,public 来源: https://blog.csdn.net/weixin_44258719/article/details/87924351