界面有点丑,可以在布局文件里优化一下
使用的依赖和权限
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2' implementation 'io.reactivex.rxjava2:rxjava:2.1.12' implementation 'com.jakewharton.rxbinding2:rxbinding:2.1.1' implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0' implementation 'com.squareup.retrofit2:retrofit:2.4.0' implementation 'com.squareup.retrofit2:converter-gson:2.4.0' implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0' implementation 'com.facebook.fresco:fresco:0.12.0' // 支持 GIF 动图,需要添加 implementation 'com.facebook.fresco:animated-gif:0.12.0' implementation 'com.android.support:support-v4:27.1.1' implementation 'com.sunfusheng:marqueeview:1.3.3' implementation 'com.jcodecraeer:xrecyclerview:1.3.2' implementation 'com.youth.banner:banner:1.4.10' implementation 'com.android.support:design:27.1.1' implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.0.4-7' implementation 'com.jakewharton:butterknife:8.8.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1' implementation 'com.github.bumptech.glide:glide:4.5.0' implementation 'org.greenrobot:eventbus:3.0.0'
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name="android.permission.READ_PHONE_STATE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/> <uses-permission android:name="android.permission.CAMERA"/>
activity_main
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <android.support.v4.widget.SwipeRefreshLayout android:id="@+id/my_srl" android:layout_width="match_parent" android:layout_height="match_parent"> <com.jcodecraeer.xrecyclerview.XRecyclerView android:id="@+id/xrecyel_view" android:layout_width="wrap_content" android:layout_height="wrap_content"> </com.jcodecraeer.xrecyclerview.XRecyclerView> </android.support.v4.widget.SwipeRefreshLayout> </LinearLayout>
item_layout
<?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="100dp"> <TextView android:id="@+id/text_title" android:layout_marginTop="8sp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="111"/> <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/simle_view" android:layout_width="100dp" android:layout_height="100dp" android:layout_marginLeft="10dp" android:layout_toRightOf="@id/text_title"/> </RelativeLayout>
item_layout02
<?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"> <TextView android:id="@+id/title_view" android:layout_marginTop="8sp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="111"/> <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/simpledrawee" android:layout_marginTop="10dp" android:layout_width="380dp" android:layout_height="140dp" /> </LinearLayout>
MainActivity
import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import com.bwie.test.adapter.MyAdapter; import com.bwie.test.bean.BaBean; import com.bwie.test.evens.Evens; import com.bwie.test.presenter.MyDataPersenter; import com.bwie.test.utils.OkhttpUtils; import com.bwie.test.utils.OnNetListener; import com.google.gson.Gson; import com.jcodecraeer.xrecyclerview.XRecyclerView; import org.greenrobot.eventbus.EventBus; import java.util.List; public class MainActivity extends AppCompatActivity implements DataView,MyAdapter.OnClickListener{ private String url = "http://api.tianapi.com/nba/?key=71e58b5b2f930eaf1f937407acde08fe&num=10"; private XRecyclerView xrecyel_view; private MyAdapter myAdapter; private List<BaBean.NewslistBean> list; private SwipeRefreshLayout my_srl; Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); list = (List<BaBean.NewslistBean>) msg.obj; myAdapter = new MyAdapter(MainActivity.this, list); xrecyel_view.setAdapter(myAdapter); //调用适配器中的点击事件 myAdapter.OnClick((MyAdapter.OnClickListener) MainActivity.this); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //查找控件 xrecyel_view = findViewById(R.id.xrecyel_view); my_srl = findViewById(R.id.my_srl); my_srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { //控制使它显示刷新 my_srl.setRefreshing(true); } }); //设置管理器 xrecyel_view.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)); //初始化P层,将url和本类传过去 MyDataPersenter persenter = new MyDataPersenter(this); persenter.netWork(url); } @Override public void OnItemClick(int position) { Evens evens = new Evens(); String title = list.get(position).getTitle(); String url = list.get(position).getUrl(); evens.setName(title); EventBus.getDefault().postSticky(evens); // //实现跳转 // Intent intent = new Intent(MainActivity.this, Main2Activity.class); // startActivity(intent); } @Override public void toBackHome(List<BaBean.NewslistBean> list) { Message msg = new Message(); msg.obj = list; handler.sendMessage(msg); my_srl.setRefreshing(false); } }
DataView
import com.bwie.test.bean.BaBean; import java.util.List; public interface DataView { //接收数据的方法 void toBackHome(List<BaBean.NewslistBean> list); }
app文件夹下MyApp
import android.app.Application; import com.facebook.drawee.backends.pipeline.Fresco; public class MyApp extends Application{ @Override public void onCreate() { super.onCreate(); //初始化fresco Fresco.initialize(this); } }
adapter文件夹下MyAdapter
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.bwie.test.bean.BaBean; import com.bwie.test.jinfengkai20180613.R; import com.facebook.drawee.view.SimpleDraweeView; import java.util.List; public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{ private Context context; private List<BaBean.NewslistBean> list; public MyAdapter(Context context, List<BaBean.NewslistBean> list) { this.context = context; this.list = list; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view; //判断条目的类型 判断引入的布局文件 int itemViewType = getItemViewType(viewType); if(itemViewType==0){ view = View.inflate(context, R.layout.item_layout, null); }else{ view = View.inflate(context, R.layout.item_layout02, null); } MyViewHolder myViewHolder = new MyViewHolder(view); return myViewHolder; } //获取条目的类型 然后进行判断 @Override public int getItemViewType(int position) { if(position%2==0){ return 0; }else { return 1; } } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder,final int position) { MyViewHolder myViewHolder = (MyViewHolder) holder; //得到条目 int itemViewType = getItemViewType(position); if(itemViewType==0){ myViewHolder.text_title.setText(list.get(position).getTitle()); myViewHolder.simle_view.setImageURI(list.get(position).getPicUrl()); }else{ myViewHolder.title_view.setText(list.get(position).getTitle()); myViewHolder.simpledrawee.setImageURI(list.get(position).getPicUrl()); } //条目进行点击事件 myViewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onClickListener.OnItemClick(position); } }); } @Override public int getItemCount() { return list.size(); } //创建暴露点击事件的类 OnClickListener onClickListener; public void OnClick(OnClickListener onClickListener){ this.onClickListener=onClickListener; } //创建点击事件接口 public interface OnClickListener{ void OnItemClick(int position); } class MyViewHolder extends RecyclerView.ViewHolder{ private final TextView text_title,title_view; private final SimpleDraweeView simle_view; private final SimpleDraweeView simpledrawee; public MyViewHolder(View view) { super(view); //找到两个子布局文件的控件id simle_view = view.findViewById(R.id.simle_view); text_title = view.findViewById(R.id.text_title); simpledrawee = view.findViewById(R.id.simpledrawee); title_view = view.findViewById(R.id.title_view); } } }
model文件夹下DataModel
import com.bwie.test.presenter.MyDataPersenter; public interface DataModel { //请求数据的方法 void getData(String url, MyDataPersenter presenter); }
MyDataModel
import com.bwie.test.bean.BaBean; import com.bwie.test.presenter.MyDataPersenter; import com.bwie.test.utils.OkhttpUtils; import com.google.gson.Gson; import java.io.IOException; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class MyDataModel implements DataModel{ @Override public void getData(String url,final MyDataPersenter presenter) { OkhttpUtils.doGet(url, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String json = response.body().string(); Gson gson = new Gson(); BaBean baBean = gson.fromJson(json, BaBean.class); List<BaBean.NewslistBean> list = baBean.getNewslist(); presenter.Success(list); } }); } }
presenter文件夹下DataPresenter
import com.bwie.test.bean.BaBean; import java.util.List; public interface DataPresenter { //成功与失败的方法 void Success(List<BaBean.NewslistBean> list); void Error(); }
MyDataPersenter
import com.bwie.test.bean.BaBean; import com.bwie.test.jinfengkai20180613.DataView; import com.bwie.test.model.MyDataModel; import java.util.List; public class MyDataPersenter implements DataPresenter{ //创建构造器 DataView dataView; private final MyDataModel model; public MyDataPersenter(DataView dataView) { this.dataView = dataView; model = new MyDataModel(); } @Override public void Success(List<BaBean.NewslistBean> list) { //调用V层接收数据的方法 dataView.toBackHome(list); } @Override public void Error() { } //接收url public void netWork(String url){ //调用M层请求数据的方法 model.getData(url,this); } }
utils文件夹下OnNetListener
public interface OnNetListener { void onSuccess(String result); void onFailed(Exception e); }
MyInterceptor
import java.io.IOException; import okhttp3.FormBody; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; public class MyInterceptor implements Interceptor{ @Override public Response intercept(Chain chain) throws IOException { Response response; //区分是GET请求还是POST请求 Request originRequest = chain.request(); if ("GET".equals(originRequest.method())) { HttpUrl httpUrl = originRequest.url() .newBuilder() .addQueryParameter("source", "android") .build(); Request request = new Request.Builder().url(httpUrl).build(); //发送请求 response = chain.proceed(request); } else { FormBody.Builder builder = new FormBody.Builder(); FormBody body = (FormBody) originRequest.body(); int size = body.size(); for (int i = 0; i < size; i++) { builder.add(body.name(i), body.value(i)); } builder.add("source", "android"); FormBody formBody = builder.build(); Request request = new Request.Builder() .url(originRequest.url()) .post(formBody) .build(); response = chain.proceed(request); } return response; } }
OkhttpUtils
import android.os.Environment; import android.os.Handler; import android.os.Looper; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.concurrent.TimeUnit; import okhttp3.Cache; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; public class OkhttpUtils { private OkhttpUtils(){}; static OkHttpClient client; public static OkHttpClient getInstance(){ if (client==null) { //更加安全 synchronized (OkhttpUtils.class) { //缓存的地方 mnt/sdcard File file = new File(Environment.getExternalStorageDirectory(), "cache11"); client = new OkHttpClient().newBuilder() .readTimeout(3000, TimeUnit.SECONDS) //设置读取超时时间 .connectTimeout(3000, TimeUnit.SECONDS) //设置连接的超时时间 .cache(new Cache(file, 10 * 1024)) .build(); } } return client; } /** * get请求 * Callback 是一个接口 */ public static void doGet(String url, Callback callback){ OkHttpClient client = getInstance(); Request request = new Request.Builder() .url(url) .build(); client.newCall(request).enqueue(callback); } //post请求 /** * @param url 请求的地址 * @param parms 请求的参数 * @param callback callback */ public static void doPost(String url, Map<String,String> parms, Callback callback){ OkHttpClient client = getInstance(); FormBody.Builder body = new FormBody.Builder(); //key value for (String key:parms.keySet()){ //value的值 body.add(key,parms.get(key)); } Request request = new Request.Builder() .url(url) .post(body.build()) .build(); client.newCall(request).enqueue(callback); } //用来上传图片的 //url , 图片 ,参数 Callback public static void upImage(String url, File file, String filenName, Map<String,String> params, Callback callback){ OkHttpClient client = getInstance(); //requestBody的实现类 Formbody MultipartBody.Builder builder = new MultipartBody.Builder(); if (params!=null){ for (String key :params.keySet()){ builder.addFormDataPart(key,params.get(key)); } } //设置类型 builder.setType(MultipartBody.FORM); builder.addFormDataPart("file",filenName, RequestBody.create(MediaType.parse( "application/octet-stream"),file)); Request request = new Request.Builder() .url(url) .post(builder.build()) .build(); client.newCall(request).enqueue(callback); } }
evens文件夹下Evens
public class Evens { private String name; private int url; private int url2; public int getUrl2() { return url2; } public void setUrl2(int url2) { this.url2 = url2; } public int getUrl() { return url; } public void setUrl(int url) { this.url = url; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
bean文件夹下BaBean
import java.util.List; public class BaBean { private int code; private String msg; private List<NewslistBean> newslist; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public List<NewslistBean> getNewslist() { return newslist; } public void setNewslist(List<NewslistBean> newslist) { this.newslist = newslist; } public static class NewslistBean { private String ctime; private String title; private String description; private String picUrl; private String url; public String getCtime() { return ctime; } public void setCtime(String ctime) { this.ctime = ctime; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } }