Android项目okhttp请求+RecyclerView展示

来源:互联网 发布:华为手机免费网络硬盘 编辑:程序博客网 时间:2024/06/05 22:54

准备阶段:
1.网络请求使用okhttp:

compile'xyz.reginer.http:httplib:1.0.4'

2.界面展示使用RecyclerView:

compile 'xyz.reginer.baseadapter:baseadapter:1.1.2'compile 'com.android.support:recyclerview-v7:25.0.0'

3.数据传递使用EventBus:

compile 'org.greenrobot:eventbus:3.0.0'

4.解析json使用Gson:

compile 'com.google.code.gson:gson:2.8.0'

5.图片展示使用Glide:

compile 'com.github.bumptech.glide:glide:3.7.0'

开始撸代码:
1.使用RHttp请求网络数据并使用Gson解析同时使用EventBus传递数据:

public static void getJson() {        RHttp.get().url("http://www.reginer.xyz/json/").build().execute(new BaseCallBack<Content>(Content.class) {            @Override            public void onError(Call call, Exception e, int id) {            }            @Override            public void onResponse(Content response, int id) {                EventBus.getDefault().post(response);            }        });    }

如若携带参数可.params()或者.addParams()添加。

2.在BaseCallBack中解析json:

public abstract class BaseCallBack<T> extends Callback<T> {    private Class<T> clazz;    protected BaseCallBack(Class<T> clazz) {        this.clazz = clazz;    }    @Override    public T parseNetworkResponse(Response response, int id) throws Exception {        String string = response.body().string();        return json2Bean(string, clazz);    }    /**     * 将json映射成bean对象     *     * @param result     *            json字符串     * @param clazz     *            bean对象字节码     */    private static  <T> T json2Bean(String result, Class<T> clazz) {        if (TextUtils.isEmpty(result))            return null;        Gson gs = new Gson();        return gs.fromJson(result, clazz);    }}

3.创建adapter继承自CommonRvAdapter。

public class ContentAdapter extends CommonRvAdapter<Content.ItemBean>{    public ContentAdapter(Context context, int layoutResId, List<Content.ItemBean> data) {        super(context, layoutResId, data);    }    @Override    public void convert(BaseAdapterHelper helper, Content.ItemBean item, int position) {    }}

如若根据item的不同类型显示不同布局,可重写getLayoutResId方法:

@Override    public int getLayoutResId(Content.ItemBean item, int position) {        switch (item.getType()) {            case 1:                return R.layout.view_type1_layout;            case 2:                return R.layout.view_type2_layout;        }        return 0;    }

在convert方法中设置控件内容:

@Override    public void convert(BaseAdapterHelper helper, Content.ItemBean item, int position) {        switch (item.getType()) {            case 1:                Glide.with(helper.getView().getContext()).load(item.getImage()).                        centerCrop().crossFade().into((ImageView) helper.getView(R.id.iv_content));                helper.setText(R.id.tv_content, item.getName());                break;            case 2:                helper.setText(R.id.tv_content, item.getName());                helper.setText(R.id.tv_description, item.getDescription());                break;        }    }

4.在activity中初始化控件:

private void initView() {        mList = new ArrayList<>();        mAdapter = new ContentAdapter(this,-1,mList);        RecyclerView mRvContent = (RecyclerView) findViewById(R.id.rv_content);        mRvContent.setLayoutManager(new LinearLayoutManager(this));        //设置分割线        mRvContent.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));        mRvContent.setAdapter(mAdapter);    }

注册EventBus:
在onCreate中

EventBus.getDefault().register(this);

在onDestroy中

EventBus.getDefault().unregister(this);

或者在onStart(),onStop()中。

获取EventBus返回值,刷新Adapter:

@Subscribe(threadMode = ThreadMode.MAIN)    public void getContent(Content content) {         if (content.getCode()==200){             mList.addAll(content.getItem());             mAdapter.notifyDataSetChanged();         }    }

开始请求数据:

NetManager.getJson();

效果图:
效果图

添加item点击事件:

mAdapter.setOnItemClickListener(this);@Override    public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int position) {        Toast.makeText(this,"position is::"+position,Toast.LENGTH_SHORT).show();    }

添加item子项控件点击事件:
在Adapter的convert方法内添加:

setOnItemChildClickListener(helper,position,R.id.iv_content,R.id.tv_content);

Activity中添加:

mAdapter.setOnItemChildClickListener(this);@Override    public void onChildClick(View v, int position) {        switch (v.getId()) {                case R.id.iv_content:                    Toast.makeText(this,"picture position is::"+position,Toast.LENGTH_SHORT).show();                    break;                default:                    Toast.makeText(this,"child position is::"+position,Toast.LENGTH_SHORT).show();                    break;                }    }

源码在这里

————————完结——————————

0 0