美文网首页
Android组件RecyclerView的使用方法

Android组件RecyclerView的使用方法

作者: i宁静的鱼 | 来源:发表于2019-08-10 11:18 被阅读0次
  1. 创建RecyclerView的布局文件activity_recycler.xml
<?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="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
  1. 创建单条item的布局文件activity_recycler_item.xml
<?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="match_parent"
    android:paddingTop="5dp">

    <TextView
        android:id="@+id/coursename"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:textStyle="bold"
        android:layout_marginStart="110dp"
        android:ellipsize="end"
        android:singleLine="true" />
    <TextView
        android:id="@+id/teachername"
        android:layout_below="@id/coursename"
        android:textSize="16sp"
        android:layout_marginStart="110dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:singleLine="true" />
    <TextView
        android:id="@+id/studentnum"
        android:textSize="16sp"
        android:layout_below="@id/teachername"
        android:layout_marginStart="110dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:singleLine="true" />

    <ImageView
        android:id="@+id/courselogo"
        android:layout_width="100dp"
        android:layout_height="65dp"
        android:layout_marginStart="5dp"
        android:scaleType="centerCrop"
        android:contentDescription="@string/app_name" />

    <View
        android:layout_below="@id/courselogo"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:background="@color/colorPrimary"/>

</RelativeLayout>
  1. 创建RecyclerView的activity类
package com.iefeel.yudemo;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.iefeel.tools.YuRecyclerAdapter;
import com.mumu.dialog.MMAlertDialog;

import java.util.ArrayList;
import java.util.HashMap;

public class RecyclerActivity extends BaseActivity {

    //定义数组以填充数据
    private String[][] coursedata = {
            {"722", "物联网硬件基础1", "教师三", "1111", "http://xuexi.iefeel.com/userfiles/logo/201903/30/7e723fc7a3aa607502c502b6f9fc2ea7_s.jpg"},
            {"720", "基于LabVIEW的物联网程序设计", "教师二", "2222", "http://xuexi.iefeel.com/userfiles/logo/201903/30/7710e65597136cdd3465e2211edeb90f_s.jpg"},
            {"658", "建筑装饰表现技法", "教师一", "3333", "http://xuexi.iefeel.com/public/images/course.png"}
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler);

        //定义一个HashMap构成的列表以键值对的方式存放数据
        ArrayList<HashMap<String, Object>> listItem = new ArrayList<>();
        //循环填充数据
        for(int i=0;i<coursedata.length;i++){
            HashMap<String,Object> map = new HashMap<>();
            map.put("courseid", coursedata[i][0]);
            map.put("coursename", coursedata[i][1]);
            map.put("teachername", "主讲:" + coursedata[i][2]);
            map.put("studentnum", "学员:" + coursedata[i][3]);
            map.put("courselogo", coursedata[i][4]);
            listItem.add(map);
        }

        RecyclerView recyclerv = findViewById(R.id.recycler_view);
        LinearLayoutManager layomanager = new LinearLayoutManager(this);
        recyclerv.setLayoutManager(layomanager);
        YuRecyclerAdapter madapter = new YuRecyclerAdapter(RecyclerActivity.this, listItem);
        recyclerv.setAdapter(madapter);
        madapter.setOnItemClickListener(new YuRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int Position) {
                String s = listItem.get(Position).toString();
                MMAlertDialog.showDialog(RecyclerActivity.this,
                        "这是第"+ (Position+1) +"个item",
                        s,
                        null,
                        "确定",
                        false,
                        null,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(RecyclerActivity.this, "确定", Toast.LENGTH_SHORT).show();
                                dialog.dismiss();
                            }
                        });
            }
        });
    }

}
  1. 自定义RecyclerView的adapter
package com.iefeel.tools;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.iefeel.yudemo.R;

public class YuRecyclerAdapter extends RecyclerView.Adapter<YuRecyclerAdapter.YuViewHolder> {

    //当前上下文对象
    Context context;
    //RecyclerView填充Item数据的List对象
    ArrayList<HashMap<String, Object>> datas;
    private YuViewHolder holder;

    RemoteImageHelper imghelper = new RemoteImageHelper();

    public YuRecyclerAdapter(Context context, ArrayList<HashMap<String, Object>> datas){
        this.context = context;
        this.datas = datas;
    }

    //创建ViewHolder
    @NonNull
    @Override
    public YuViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //实例化得到Item布局文件的View对象
        View v = View.inflate(context, R.layout.activity_recycler_item,null);
        //返回YuViewHolder的对象
        return new YuViewHolder(v);
    }

    private OnItemClickListener mItemClickListener;
    //item的回调接口
    public interface OnItemClickListener {
        void onItemClick(View view, int Position);
    }
    //定义一个设置点击监听器的方法
    public void setOnItemClickListener(OnItemClickListener itemClickListener) {
        this.mItemClickListener = itemClickListener;
    }

    //绑定数据
    @Override
    public void onBindViewHolder(@NonNull YuViewHolder holder, int position) {
        holder.coursename.setText(datas.get(position).get("coursename").toString());
        holder.teachername.setText(datas.get(position).get("teachername").toString());
        holder.studentnum.setText(datas.get(position).get("studentnum").toString());
        imghelper.loadImage(holder.courselogo, datas.get(position).get("courselogo").toString());
        //如果设置了回调,则设置点击事件
        if (mItemClickListener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mItemClickListener.onItemClick(holder.itemView, position);
                }
            });
        }
    }

    //返回Item的数量
    @Override
    public int getItemCount() {
        return datas.size();
    }

    //继承RecyclerView.ViewHolder抽象类的自定义ViewHolder
    class YuViewHolder extends RecyclerView.ViewHolder{
        TextView coursename;
        TextView teachername;
        TextView studentnum;
        ImageView courselogo;

        public YuViewHolder(View itemView) {
            super(itemView);
            coursename = itemView.findViewById(R.id.coursename);
            teachername = itemView.findViewById(R.id.teachername);
            studentnum = itemView.findViewById(R.id.studentnum);
            courselogo = itemView.findViewById(R.id.courselogo);
        }
    }
    
}
  1. 获取网络图片辅助类
package com.iefeel.tools;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import com.iefeel.yudemo.R;

public class RemoteImageHelper {

    private final Map<String, Drawable> cache = new HashMap<String, Drawable>();

    public void loadImage(final ImageView imageView, final String urlString) {
        loadImage(imageView, urlString, true);
    }

    public void loadImage(final ImageView imageView, final String urlString, boolean useCache) {
        if (useCache && cache.containsKey(urlString)) {
            imageView.setImageDrawable(cache.get(urlString));
        }

        //You may want to show a "Loading" image here
        imageView.setImageResource(R.drawable.ic_launcher);

        //Log.d(this.getClass().getSimpleName(), "Image url:" + urlString);

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message message) {
                imageView.setImageDrawable((Drawable) message.obj);
            }
        };

        Runnable runnable = new Runnable() {
            public void run() {
                Drawable drawable = null;
                try {
                    InputStream is = download(urlString);
                    drawable = Drawable.createFromStream(is, "src");

                    if (drawable != null) {
                        cache.put(urlString, drawable);
                    }
                } catch (Exception e) {
                    Log.e(this.getClass().getSimpleName(), "Image download failed", e);
                    //Show "download fail" image
                    drawable = imageView.getResources().getDrawable(R.drawable.ic_launcher);
                }

                //Notify UI thread to show this image using Handler
                Message msg = handler.obtainMessage(1, drawable);
                handler.sendMessage(msg);
            }
        };
        new Thread(runnable).start();

    }

    /**
     * Download image from given url.
     * Make sure you have "android.permission.INTERNET" permission set in AndroidManifest.xml.
     *
     * @param urlString
     * @return
     * @throws MalformedURLException
     * @throws IOException
     */
    private InputStream download(String urlString) throws MalformedURLException, IOException {
        InputStream inputStream = (InputStream) new URL(urlString).getContent();
        return inputStream;
    }
}
  1. 运行结果


    RecyclerView效果图.jpg
  2. item点击事件
    RecyclerView点击事件.jpg
    更多内容点此查看。

相关文章

网友评论

      本文标题:Android组件RecyclerView的使用方法

      本文链接:https://www.haomeiwen.com/subject/osoljctx.html