主页面
package com.example.lx_recycleview; import android.annotation.SuppressLint; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.os.Handler; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.View; import android.widget.Adapter; import android.widget.Button; import com.google.gson.Gson; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final int SUCCESS = 492; private Button ll; private Button bg; private Button pb; private RecyclerView rv; private MyAdapter myAdapter; private List<SuperClass.DataBean.PcFeedFocusBean> list; @SuppressLint("HandlerLeak") Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case SUCCESS: String json = (String) msg.obj; Gson gson = new Gson(); SuperClass superClass = gson.fromJson(json, SuperClass.class); list = superClass.getData().getPc_feed_focus(); myAdapter = new MyAdapter(list, MainActivity.this); rv.setAdapter(myAdapter); } } }; private Button add; private Button select; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { ll = findViewById(R.id.ll); bg = findViewById(R.id.bg); pb = findViewById(R.id.pb); rv = findViewById(R.id.rv); add = findViewById(R.id.add); select = findViewById(R.id.select); ll.setOnClickListener(this); bg.setOnClickListener(this); pb.setOnClickListener(this); add.setOnClickListener(this); select.setOnClickListener(this); } //按钮监听 @Override public void onClick(View v) { switch (v.getId()){ case R.id.ll: getpostll(); //线性布局管理器 rv.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)); break; case R.id.bg: //表格布局管理器 rv.setLayoutManager(new GridLayoutManager(this,3)); break; case R.id.pb: //瀑布式布局管理器 rv.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)); break; case R.id.add: //添加 myAdapter.additem(list.get(0)); break; case R.id.select: //删除 myAdapter.delete(0); break; } } //解析 public void getpostll() { OkHttpClient client = new OkHttpClient(); Request builder = new Request.Builder() .url("https://www.toutiao.com/api/pc/focus/") .build(); client.newCall(builder).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { //得到数据并转型 String s = response.body().string(); //更新UI不能在子线程中,使用Handler Message message = handler.obtainMessage(); message.obj = s; message.what = SUCCESS; handler.sendMessage(message); } }); return ; } }
图片类
package com.example.lx_recycleview; import android.app.Application; import android.os.Environment; import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer; import java.io.File; /** * data:2018/05/21. * author : 殷成龙(Administrator) * function :图片工具类 */ public class App extends Application { @Override public void onCreate() { super.onCreate(); File file = new File(Environment.getExternalStorageDirectory() + "/" + "image"); ImageLoaderConfiguration build = new ImageLoaderConfiguration.Builder(this) //设置缓存地址 .diskCache(new UnlimitedDiskCache(file)) //关联getimg .defaultDisplayImageOptions(getimg()) //内存缓存20M .memoryCacheSize(2 * 1024 * 1024) //可以缓存文件数量 .diskCacheFileCount(100) //线程池数量 .threadPoolSize(3) .build(); ImageLoader.getInstance().init(build); } public DisplayImageOptions getimg() { DisplayImageOptions img = new DisplayImageOptions.Builder() //加载时显示的图片 .showImageOnLoading(R.mipmap.ic_launcher) .showImageOnFail(R.mipmap.ic_launcher) .showImageForEmptyUri(R.mipmap.ic_launcher) //设置圆角 .displayer(new RoundedBitmapDisplayer(25)) .build(); return img; } }
数据类
package com.example.lx_recycleview; import java.util.List; /** * data:2018/05/23. * author : 殷成龙(Administrator) * function : */ public class SuperClass { /** * message : success * data : {"pc_feed_focus":[{"title":"从改革地标看中国改革开放40年","display_url":"/group/6558446792944386563/","has_video":false,"image_url":"//p3.pstatp.com/origin/85fa0014ef193bffed3d","has_image":true,"group_id":6558446792944386563,"media_url":"http://toutiao.com/m4377795668"},{"title":"3年1500封情书定终身,\u201c兵哥哥\u201d开面馆救重症妻","display_url":"/group/6557993092882891277/","has_video":false,"image_url":"//p3.pstatp.com/origin/85fa0011f5feb4153842","has_image":true,"group_id":6557993092882891277,"media_url":"http://toutiao.com/m1562542894927874"},{"title":"被张翰\u201c斯文败类\u201dLOOK震惊,这次要Pick虐心又虐狗的塘主","display_url":"/group/6558457737871622664/","has_video":false,"image_url":"//p9.pstatp.com/origin/85f900153cddde3b9503","has_image":false,"group_id":6558457737871622664,"media_url":"http://toutiao.com/m5486350548"},{"title":"2018年汤姆斯杯A组次轮 中国队5比0战胜印度队","display_url":"/group/6558456235866194436/","has_video":false,"image_url":"//p3.pstatp.com/origin/85fd00061bbc829c2a33","has_image":true,"group_id":6558456235866194436,"media_url":"http://toutiao.com/m6967144588"},{"title":"大事情!陆军400将校为何齐聚库尔勒","display_url":"/group/6558390521088180743/","has_video":false,"image_url":"//p3.pstatp.com/origin/85fb0014f394d847081e","has_image":false,"group_id":6558390521088180743,"media_url":"http://toutiao.com/m4377795668"},{"title":"林志玲随便一拍都是大片,卖萌比V仙气十足","display_url":"/group/6558322997449458189/","has_video":false,"image_url":"//p3.pstatp.com/origin/85f80014e9cf1725b03a","has_image":true,"group_id":6558322997449458189,"media_url":"http://toutiao.com/m50266454509"},{"title":"托雷斯用梅开二度告别床单军团 讲话哽咽掩面拭泪","display_url":"/group/6557865406713823758/","has_video":false,"image_url":"//p1.pstatp.com/origin/85f8000ef980b72b3f99","has_image":true,"group_id":6557865406713823758,"media_url":"http://toutiao.com/m6675759548"},{"title":"Billboard 音乐奖红毯 霉霉发表获奖感言","display_url":"/group/6557876196451811844/","has_video":false,"image_url":"//p3.pstatp.com/origin/85f8000ef974b9d760ac","has_image":true,"group_id":6557876196451811844,"media_url":"http://toutiao.com/m5738017030"},{"title":"霍思燕真的是嫁给爱情了!杜江满脸宠溺成\u201c盯妻狂魔\u201d","display_url":"/group/6557876169033646595/","has_video":false,"image_url":"//p1.pstatp.com/large/85fc0003f4849c62b3bf","has_image":true,"group_id":6557876169033646595,"media_url":"http://toutiao.com/m5738017030"}]} */ private String message; private DataBean data; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public DataBean getData() { return data; } public void setData(DataBean data) { this.data = data; } public static class DataBean { private List<PcFeedFocusBean> pc_feed_focus; public List<PcFeedFocusBean> getPc_feed_focus() { return pc_feed_focus; } public void setPc_feed_focus(List<PcFeedFocusBean> pc_feed_focus) { this.pc_feed_focus = pc_feed_focus; } public static class PcFeedFocusBean { /** * title : 从改革地标看中国改革开放40年 * display_url : /group/6558446792944386563/ * has_video : false * image_url : //p3.pstatp.com/origin/85fa0014ef193bffed3d * has_image : true * group_id : 6558446792944386563 * media_url : http://toutiao.com/m4377795668 */ private String title; private String display_url; private boolean has_video; private String image_url; private boolean has_image; private long group_id; private String media_url; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDisplay_url() { return display_url; } public void setDisplay_url(String display_url) { this.display_url = display_url; } public boolean isHas_video() { return has_video; } public void setHas_video(boolean has_video) { this.has_video = has_video; } public String getImage_url() { return image_url; } public void setImage_url(String image_url) { this.image_url = image_url; } public boolean isHas_image() { return has_image; } public void setHas_image(boolean has_image) { this.has_image = has_image; } public long getGroup_id() { return group_id; } public void setGroup_id(long group_id) { this.group_id = group_id; } public String getMedia_url() { return media_url; } public void setMedia_url(String media_url) { this.media_url = media_url; } } } }
适配器
package com.example.lx_recycleview; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.nostra13.universalimageloader.core.ImageLoader; import java.util.List; /** * data:2018/05/23. * author : 殷成龙(Administrator) * function : */ public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{ private List<SuperClass.DataBean.PcFeedFocusBean> list; private Context context; //接口对象 private OnItemLongClickListener onItemLongClickListener; private OnItemClickListener onItemClickListener; public MyAdapter(List<SuperClass.DataBean.PcFeedFocusBean> list, Context context) { this.list = list; this.context = context; } //获取子布局 @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false); ViewHolder viewHolder = new ViewHolder(view); return viewHolder; } //给控件赋值 @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.tv.setText(list.get(position).getTitle()); ImageLoader.getInstance().displayImage(list.get(position).getImage_url(),holder.img); if (onItemClickListener != null) { holder.itemView.setOnClickListener(new MyOnClickListener(position, list.get(position).getTitle())); } if (onItemLongClickListener != null) { holder.itemView.setOnLongClickListener(new MyOnLongClickListener(position, list.get(position).getImage_url())); } } @Override public int getItemCount() { return list.size(); } //添加 public void additem(SuperClass.DataBean.PcFeedFocusBean s){ list.add(s); notifyDataSetChanged(); } //删除 public void delete(int index){ list.remove(index); notifyDataSetChanged(); } //ViewHodler类 class ViewHolder extends RecyclerView.ViewHolder{ private final ImageView img; private final TextView tv; public ViewHolder(View itemView) { super(itemView); img = itemView.findViewById(R.id.img); tv = itemView.findViewById(R.id.tv); } } //定义一个接口 public interface OnItemClickListener { void onItemClick(View view, int position, String data); } public interface OnItemLongClickListener { void onItemLongClick(View view, int position, String data); } private class MyOnLongClickListener implements View.OnLongClickListener { private int position; private String data; public MyOnLongClickListener(int position, String data) { this.position = position; this.data = data; } @Override public boolean onLongClick(View v) { onItemLongClickListener.onItemLongClick(v, position, data); return true; } } private class MyOnClickListener implements View.OnClickListener { private int position; private String data; public MyOnClickListener(int position, String data) { this.position = position; this.data = data; } @Override public void onClick(View v) { onItemClickListener.onItemClick(v, position, data); } } }
主页面布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:orientation="vertical" 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" tools:context="com.example.lx_recycleview.MainActivity"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="线性布局" android:id="@+id/ll"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="表格布局" android:id="@+id/bg"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="瀑布式" android:id="@+id/pb"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="添加" android:id="@+id/add"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="删除" android:id="@+id/select"/> </LinearLayout> <android.support.v7.widget.RecyclerView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rv"/> </LinearLayout>
控件布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:orientation="vertical" android:layout_marginLeft="30dp" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/img"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tv"/> </LinearLayout>
依赖
implementation 'com.android.support:recyclerview-v7:26.1.0' compile 'com.squareup.okhttp3:okhttp:3.4.2' implementation files('libs/gson-2.8.0.jar') implementation files('libs/universal-image-loader-1.9.5.jar')
清单文件
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.lx_recycleview"> <uses-permission android:name="android.permission.INTERNET"></uses-permission> <application android:name=".App" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>