Android:RecyclerView嵌套CardView应用

MainActivity中的代码:

package com.myapplication.cardviewdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 卡片布局
 * 有圆角的布局
 * <p/>
 * RecyclerView基本使用
 * 步骤:1.引入依赖的包 
 * compile 'com.android.support:recyclerview-v7:22.2.1'
 * 2.在布局里面引入控件
 * 3.代码里面查找控件
 * 4.创建适配器
 * 5.设置适配器
 */
public class MainActivity extends AppCompatActivity {
    private String path = "http://api.fengniao.com/app_ipad/news_jingxuan.php?appImei=99000505856649&osType=Android&osVersion=4.1.1&page=1";
    private List<Bean> list = new ArrayList<>();
    private RecyclerView recyclerView;
    private MyAdapter adapter;
    //控制布局显示的参数
    private RecyclerView.LayoutManager layoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        getHttp(path);
        //getHttpFast(path);
    }

    private void init() {
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        //设置显示所要显示的布局
        layoutManager = new LinearLayoutManager(this//上下文
                , LinearLayoutManager.VERTICAL//线性布局显示的方向
                , true//设置显示内容是否反转
        );
        //设置布局显示的参数
        recyclerView.setLayoutManager(layoutManager);

        adapter = new MyAdapter(list, this);
        recyclerView.setAdapter(adapter);
    }


    //原生态OkHttp下载工具
    private void getHttp(String path) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(path)
                .build();
        Call call = okHttpClient.newCall(request);
        //请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.e("===", "getHttp_onError" + e.getMessage());
            }

            @Override
            public void onResponse(Response response) throws IOException {
                String jsonString = response.body().string();
                if (!TextUtils.isEmpty(jsonString)) {
                    List<Bean> beanList = jsonToList(jsonString);
                    list.clear();
                    list.addAll(beanList);
                    //list.addAll(jsonToList(jsonString));
                    //此时是在子线程,通知主线程更新数据
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                        }
                    });
                }
            }
        });
    }

    //用fastJson解析字符串
    private List<Bean> jsonToList(String s) {
        JSONObject object = JSON.parseObject(s);
        JSONArray array = object.getJSONArray("160120");
        List<Bean> beanList = JSON.parseArray(array.toString(), Bean.class);
        return beanList;
    }

    //下载json字符串。这是hongyang大神封装好的工具。详见:https://github.com/hongyangAndroid/okhttp-utils
    private void getHttpFast(String path) {
        OkHttpUtils.get()
                .url(path)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(okhttp3.Call call, Exception e) {
                        Log.e("===", "getHttpFast_onError" + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response) {
                        if (!TextUtils.isEmpty(response)) {
                            List<Bean> beanList = jsonToList(response);
                            list.clear();
                            list.addAll(beanList);
                        }
                    }
                });
    }
}

MyAdapter中的代码:

package com.myapplication.cardviewdemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;

import java.util.List;

import okhttp3.Call;

/**
 * Created by Administrator on 2016/3/16.
 * 1.继承RecyclerView.Adapter<这里写holder>(一个写自己创建的,用原生的后面赋值的时候转)
 * 2.实现继承之后的方法
 * <p/>
 * getItemCount显示条目个数
 * onCreateViewHolder创建一个布局holder进行绑定
 * onBindViewHolder数据绑定
 */
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<Bean> list;
    private LayoutInflater mInflater;

    public MyAdapter(List<Bean> list, Context context) {
        this.list = list;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    //创建holder进行绑定
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //加载出item布局
        View view = mInflater.inflate(R.layout.item, parent, false);
        //将创建的布局设置给holder,进行绑定
        MyHolder holder = new MyHolder(view);
        return holder;
    }

    //数据设置
    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        //设置具体数据
        String title = list.get(position).getTitle();//文章标题
        ((MyHolder) holder).textView.setText(title);
        String pic_url = list.get(position).getPic_url();//图片网络地址
        //下载图片
        OkHttpUtils
                .get()
                .url(pic_url)
                .build()
                .execute(new BitmapCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        Log.e("===", "onError" + e.getMessage());
                    }

                    @Override
                    public void onResponse(Bitmap response) {
                        ((MyHolder) holder).imageView.setImageBitmap(response);
                    }
                });
    }

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

    //写一个自己的holder继承Recyclerview.ViewHolder
    public class MyHolder extends RecyclerView.ViewHolder {
        private ImageView imageView;
        private TextView textView;

        public MyHolder(View itemView) {
            super(itemView);
            imageView = (ImageView) itemView.findViewById(R.id.img_show);
            textView = (TextView) itemView.findViewById(R.id.text_show);
        }
    }
}

main_activity中代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myapplication.cardviewdemo.MainActivity"
    >

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</RelativeLayout>

item中的代码:

<?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"
              android:padding="40dp"
    >

    <android.support.v7.widget.CardView
        xmlns:card="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ff0000"
        card:cardCornerRadius="30dp"
        card:cardElevation="24dp"
        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            >

            <ImageView
                android:id="@+id/img_show"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_gravity="center"
                android:src="@mipmap/ic_launcher"
                />

            <TextView
                android:id="@+id/text_show"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/img_show"
                android:layout_gravity="center"
                />
        </LinearLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

注意build.gradle中追加:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:22.2.1'
    compile 'com.android.support:cardview-v7:22.2.1'
    compile 'com.android.support:recyclerview-v7:22.2.1'
    compile 'com.squareup.okhttp:okhttp:2.4.0'
    compile 'com.squareup.okio:okio:1.5.0'
    compile files('libs/okio-1.6.0.jar')
    compile files('libs/fastjson-1.1.33.jar')
    compile 'com.zhy:okhttputils:2.3.8'
}

libs中添加libs/fastjson-1.1.33.jar

  • 0
    点赞
  • 0
    收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:精致技术 设计师:CSDN官方博客 返回首页
评论
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值