RecyclerView列表布局

依赖:

    implementation 'com.android.support:recyclerview-v7:26.1.0'
    implementation 'com.squareup.okhttp3:okhttp:3.10.0'
    implementation 'com.google.code.gson:gson:2.2.4'
    implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
MyApp:
public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this).build();
        ImageLoader.getInstance().init(configuration);
    }
}
HttpUtilsCallback:
public interface HttpUtilsCallback {
    void onSuccess(String success);
    void onFail(int errCode, String errMsg);
}
NetUtil:
public class NetUtil implements Callback {
    private static NetUtil netUtil;
    private final OkHttpClient okHttpClient;
    private HttpUtilsCallback httpUtilsCallback;

    private NetUtil() {
        okHttpClient = new OkHttpClient.Builder().build();
    }

    public static NetUtil getInstance(){
        if (netUtil==null){
            netUtil=new NetUtil();
        }
        return netUtil;
    }

    public void doGet(String url,HttpUtilsCallback httpUtilsCallback){
        this.httpUtilsCallback=httpUtilsCallback;
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(this);
    }

    public void doPost(String url, HashMap<String,String> map, HttpUtilsCallback httpUtilsCallback){
        this.httpUtilsCallback = httpUtilsCallback;

        FormBody.Builder builder = new FormBody.Builder();

        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()){
            String key = iterator.next();
            String value = map.get(key);
            builder.add(key,value);
        }

        FormBody body = builder.build();

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(this);
    }

    @Override
    public void onFailure(Call call, IOException e) {

    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        httpUtilsCallback.onSuccess(response.body().string());
    }
}
JavaBean:
public class JavaBean {
    /**
     * error : false
     * results : [{"_id":"5aa5cc6a421aa9103ed33c7c","createdAt":"2018-03-12T08:40:10.360Z","desc":"3-12","publishedAt":"2018-03-12T08:44:50.326Z","source":"chrome","type":"福利","url":"https://ws1.sinaimg.cn/large/610dc034ly1fp9qm6nv50j20u00miacg.jpg","used":true,"who":"daimajia"},{"_id":"5a8e0c41421aa9133298a259","createdAt":"2018-02-22T08:18:09.547Z","desc":"2-22","publishedAt":"2018-02-22T08:24:35.209Z","source":"chrome","type":"福利","url":"https://ws1.sinaimg.cn/large/610dc034ly1foowtrkpvkj20sg0izdkx.jpg","used":true,"who":"代码家"},{"_id":"5a7b93d2421aa90d2cd3d7f8","createdAt":"2018-02-08T08:03:30.905Z","desc":"2-8","publishedAt":"2018-02-08T08:13:24.479Z","source":"chrome","type":"福利","url":"http://7xi8d6.com1.z0.glb.clouddn.com/20180208080314_FhzuAJ_Screenshot.jpeg","used":true,"who":"daimajia"},{"_id":"5a6e5f88421aa9115696004f","createdAt":"2018-01-29T07:40:56.269Z","desc":"1-29","publishedAt":"2018-01-29T07:53:57.676Z","source":"chrome","type":"福利","url":"http://7xi8d6.com1.z0.glb.clouddn.com/20180129074038_O3ydq4_Screenshot.jpeg","used":true,"who":"daimajia"},{"_id":"5a65381a421aa91156960022","createdAt":"2018-01-22T09:02:18.715Z","desc":"1-22","publishedAt":"2018-01-23T08:46:45.132Z","source":"chrome","type":"福利","url":"http://7xi8d6.com1.z0.glb.clouddn.com/20180122090204_A4hNiG_Screenshot.jpeg","used":true,"who":"daimajia"},{"_id":"5a5bfc29421aa9115489927b","createdAt":"2018-01-15T08:56:09.429Z","desc":"1-15","publishedAt":"2018-01-16T08:40:08.101Z","source":"chrome","type":"福利","url":"http://7xi8d6.com1.z0.glb.clouddn.com/20180115085556_8AeReR_taeyeon_ss_15_1_2018_7_58_51_833.jpeg","used":true,"who":"daimajia"},{"_id":"5a5411fb421aa90fef2035f3","createdAt":"2018-01-09T08:51:07.91Z","desc":"1-9","publishedAt":"2018-01-10T07:57:19.486Z","source":"chrome","type":"福利","url":"http://7xi8d6.com1.z0.glb.clouddn.com/20180109085038_4A7atU_rakukoo_9_1_2018_8_50_25_276.jpeg","used":true,"who":"daimajia"},{"_id":"5a443fcb421aa90fe72536ed","createdAt":"2017-12-28T08:50:19.747Z","desc":"12-28","publishedAt":"2018-01-04T13:45:57.211Z","source":"chrome","type":"福利","url":"http://7xi8d6.com1.z0.glb.clouddn.com/20171228085004_5yEHju_Screenshot.jpeg","used":true,"who":"代码家"},{"_id":"5a4ad432421aa90fe2f02d1a","createdAt":"2018-01-02T08:37:06.235Z","desc":"1-2","publishedAt":"2018-01-02T08:43:32.216Z","source":"chrome","type":"福利","url":"http://7xi8d6.com1.z0.glb.clouddn.com/20180102083655_3t4ytm_Screenshot.jpeg","used":true,"who":"daimajia"},{"_id":"5a431acd421aa90fe50c02a8","createdAt":"2017-12-27T12:00:13.664Z","desc":"12-27","publishedAt":"2017-12-27T12:13:22.418Z","source":"chrome","type":"福利","url":"http://7xi8d6.com1.z0.glb.clouddn.com/20171227115959_lmlLZ3_Screenshot.jpeg","used":true,"who":"daimajia"}]
     */

    private boolean error;
    private List<ResultsBean> results;

    public boolean isError() {
        return error;
    }

    public void setError(boolean error) {
        this.error = error;
    }

    public List<ResultsBean> getResults() {
        return results;
    }

    public void setResults(List<ResultsBean> results) {
        this.results = results;
    }

    public static class ResultsBean {
        /**
         * _id : 5aa5cc6a421aa9103ed33c7c
         * createdAt : 2018-03-12T08:40:10.360Z
         * desc : 3-12
         * publishedAt : 2018-03-12T08:44:50.326Z
         * source : chrome
         * type : 福利
         * url : https://ws1.sinaimg.cn/large/610dc034ly1fp9qm6nv50j20u00miacg.jpg
         * used : true
         * who : daimajia
         */

        private String _id;
        private String createdAt;
        private String desc;
        private String publishedAt;
        private String source;
        private String type;
        private String url;
        private boolean used;
        private String who;

        public String get_id() {
            return _id;
        }

        public void set_id(String _id) {
            this._id = _id;
        }

        public String getCreatedAt() {
            return createdAt;
        }

        public void setCreatedAt(String createdAt) {
            this.createdAt = createdAt;
        }

        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }

        public String getPublishedAt() {
            return publishedAt;
        }

        public void setPublishedAt(String publishedAt) {
            this.publishedAt = publishedAt;
        }

        public String getSource() {
            return source;
        }

        public void setSource(String source) {
            this.source = source;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public boolean isUsed() {
            return used;
        }

        public void setUsed(boolean used) {
            this.used = used;
        }

        public String getWho() {
            return who;
        }

        public void setWho(String who) {
            this.who = who;
        }
    }
}
BasePresenter:
public class BasePresenter<T extends IBaseView> {
    private T t;

    public void attachView(T t){
        this.t=t;
    }

    public T getView() {
        return t;
    }
}
MainPresenter:
public class MainPresenter extends BasePresenter<IMainView>{

    private NetUtil netUtil;

    public MainPresenter() {
        netUtil = NetUtil.getInstance();
    }

    public void getDataFromServer(String url) {
        netUtil.doGet(url, new HttpUtilsCallback() {
            @Override
            public void onSuccess(String success) {
                getView().onSuccess(success);
            }
            @Override
            public void onFail(int errCode, String errMsg) {

            }
        });
    }
}
BaseActivity:
public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity implements IBaseView {

    private P p;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(setChildContentView());
        initView();
        p=initPresenter();
        p.attachView(this);
        initData();
    }

    public P getPresenter(){
        return p;
    }

    abstract void initView();
    abstract void initData();
    abstract P initPresenter();
    abstract int setChildContentView();
}
MainActivity:
public class MainActivity extends BaseActivity<MainPresenter> implements IMainView{

    private String url="http://gank.io/api/data/福利/30/1";
    private RecyclerView rv;
    private JavaBean javaBean=new JavaBean();
    private MyAdapter adapter;
    private LinearLayoutManager linearLayoutManager;
    private GridLayoutManager gridLayoutManager;
    private StaggeredGridLayoutManager staggeredGridLayoutManager;
    boolean flag=false;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            adapter.setData(javaBean.getResults());
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    void initView() {
        rv = findViewById(R.id.rv);
    }

    @Override
    void initData() {
        //设置适配器
        adapter = new MyAdapter(MainActivity.this);
        rv.setAdapter(adapter);
        //布局管理器
        linearLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false);
        gridLayoutManager = new GridLayoutManager(MainActivity.this,3);
        staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        //设置布局
        rv.setLayoutManager(linearLayoutManager);
        //请求数据
        getPresenter().getDataFromServer(url);
    }

    @Override
    MainPresenter initPresenter() {
        return new MainPresenter();
    }

    @Override
    int setChildContentView() {
        return R.layout.activity_main;
    }

    @Override
    public void onSuccess(String s) {
        //得到数据,解析数据
        Gson gson = new Gson();
        javaBean = gson.fromJson(s, JavaBean.class);
        handler.sendEmptyMessage(0);
//        Log.e("----MainActivity---","得到数据"+"-----------------"+s);
    }

    public void huan(View view) {
        if (flag){
            rv.setLayoutManager(linearLayoutManager);
        }else {
            rv.setLayoutManager(gridLayoutManager);
        }
        flag=!flag;
        Log.e("-------",""+flag);
    }
}
MyAdapter:
public class MyAdapter extends RecyclerView.Adapter {
    private Context context;

    public MyAdapter(Context context) {
        this.context = context;
    }

    private List<JavaBean.ResultsBean> list=new ArrayList<>();

    public void setData(List<JavaBean.ResultsBean> results_list){
        list.addAll(results_list);
        notifyDataSetChanged();
        Log.e("----MyAdapter-----","适配器得到数据"+list.get(3).getUrl());
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(context).inflate(R.layout.layout_item, parent ,false);
        return new MyViewHolder(inflate);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        ImageLoader imageLoader = ImageLoader.getInstance();
        MyViewHolder viewHolder= (MyViewHolder) holder;
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnFail(R.mipmap.ic_launcher)
                .showImageOnLoading(R.mipmap.ic_launcher)
                .showImageForEmptyUri(R.mipmap.ic_launcher)
                .build();

        imageLoader.displayImage(list.get(position).getUrl(),viewHolder.img_item,options);
//        Log.e("----MyAdapter-----",list.get(position).getUrl());
//        viewHolder.text_item.setText(list.get(position).getUrl());
//        viewHolder.text_item.setText(list.get(position));
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder{

        private ImageView img_item;
//        private TextView text_item;

        public MyViewHolder(View itemView) {
            super(itemView);
            img_item = itemView.findViewById(R.id.img_item);
//            text_item = itemView.findViewById(R.id.text_item);
        }
    }
}
IBaseView:
public interface IBaseView { }
IMainView:
public interface IMainView extends IBaseView {
    void onSuccess(String s);
}
activity_main.xml:
<?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=".view.activity.MainActivity">

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="huan"
        android:text="切换"/>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>
layout_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:id="@+id/text_item"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/colorAccent"/>
    <ImageView
        android:id="@+id/img_item"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@mipmap/ic_launcher"/>
</LinearLayout>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值