RecyclerView加载图片

 这是一个完整,然后说哪些有用

 

adapter = object : BAdapter(R.layout.item_show_print_list, data) {
            var lruCache: LruCache? = null

            init {
                val cacheSize = 1024 * 1024 * 1024 / 8
                lruCache = object : LruCache(cacheSize) {
                    override fun sizeOf(value: String?, key: BitmapDrawable?): Int {
                        return key!!.getBitmap().getByteCount()
                    }
                };
            }

            fun addBitmapToMemoryCache(key: String, drawable: BitmapDrawable) {
                if (getBitmapFromMemoryCache(key) == null) {
                    lruCache!!.put(key, drawable)
                }
            }

            fun getBitmapFromMemoryCache(key: String): BitmapDrawable? {
                return lruCache!!.get(key)

            }

            inner class BitmapWorkerTask(private val mImageView: ImageView?) : AsyncTask() {

                override fun doInBackground(vararg params: String): BitmapDrawable {
                    val imageUrl = params[0]
                    // 在后台开始下载图片
                    val bitmap = downloadBitmap(imageUrl)
                    val drawable = BitmapDrawable(App.getContext().resources, bitmap)
                    addBitmapToMemoryCache(imageUrl, drawable)
                    return drawable
                }

                override fun onPostExecute(drawable: BitmapDrawable?) {
                    if (mImageView != null && drawable != null) {
                        mImageView.setImageDrawable(drawable)
                    }
                }

                /**
                 * 建立HTTP请求,并获取Bitmap对象。
                 *
                 * @param imageUrl 图片的URL地址
                 * @return 解析后的Bitmap对象
                 */
                private fun downloadBitmap(imageUrl: String): Bitmap? {
                    var bitmap: Bitmap? = null
                    var con: HttpURLConnection? = null
                    try {
                        val url = URL(imageUrl)
                        con = url.openConnection() as HttpURLConnection
                        con.connectTimeout = 5 * 1000
                        con.readTimeout = 10 * 1000
                        bitmap = BitmapFactory.decodeStream(con.inputStream)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    } finally {
                        con?.disconnect()
                    }
                    return bitmap
                }

            }

            override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): BAdapterViewHolder {
                val view = LayoutInflater.from(parent!!.context)
                        .inflate(resource, parent, false)
                return ActivityViewHolder(view)
            }

            override fun onBindViewHolder(p0: BAdapterViewHolder, position: Int) {
                val get = data.get(position)
                val holder = p0 as ActivityViewHolder
                val nextInt = Random().nextInt()
                holder.tv_item1.setText("溯源码" + nextInt)
                holder.tv_item2.setText("品牌:草原牧业")
                holder.tv_item3.setText("名称:牛小排")
                holder.tv_item4.setText("价格22元/kg")
                var url: String = imgData.get(Random().nextInt(imgData.size))
                val drawable = lruCache?.get(url)
                if (drawable != null) {
                    holder.iv_pic.setImageDrawable(drawable)
                } else {
                    val task: BitmapWorkerTask = BitmapWorkerTask(holder.iv_pic);
                    task.execute(url);
                }
                holder.mView1.setOnClickListener(object : View.OnClickListener {
                    override fun onClick(p0: View?) {
                        LAST_LINE_TEXT_PLACE_Y = dp2px(115)
                        QRCStr = nextInt.toString()
                        initPlace("溯源码" + nextInt, "溯源码", "品牌:草原牧业", "名称:牛小排", "价格22元/0kg")
                        btnLabelPrint()

                    }

                })
            }

        }
        rv.layoutManager = LinearLayoutManager(this)
        rv.itemAnimator = DefaultItemAnimator()
        rv.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
        rv.adapter = adapter
        bt_lanya.setOnClickListener(object : View.OnClickListener {
            override fun onClick(p0: View?) {
                btnBluetoothConn()
            }

        })

这个东西用来缓存图片,把图片和图片链接结合起来,为防止错位做准备

 var lruCache: LruCache? = null

            init {
                val cacheSize = 1024 * 1024 * 1024 / 8
                lruCache = object : LruCache(cacheSize) {
                    override fun sizeOf(value: String?, key: BitmapDrawable?): Int {
                        return key!!.getBitmap().getByteCount()
                    }
                };
            }

 把图片保存到缓存里

    fun addBitmapToMemoryCache(key: String, drawable: BitmapDrawable) {
                if (getBitmapFromMemoryCache(key) == null) {
                    lruCache!!.put(key, drawable)
                }
            }

 从缓存得到图片

 fun getBitmapFromMemoryCache(key: String): BitmapDrawable? {
                return lruCache!!.get(key)

            }

用来后台下载图片,并把图片缓存进缓存,然后设置图片你,这个类是从零开始下载图片,然后加进 缓存,然后设置图片到view

标记一下,这下面的是下载代码,也是下载类

 inner class BitmapWorkerTask(private val mImageView: ImageView?) : AsyncTask() {

                override fun doInBackground(vararg params: String): BitmapDrawable {
                    val imageUrl = params[0]
                    // 在后台开始下载图片
                    val bitmap = downloadBitmap(imageUrl)
                    val drawable = BitmapDrawable(App.getContext().resources, bitmap)
                    addBitmapToMemoryCache(imageUrl, drawable)
                    return drawable
                }

                override fun onPostExecute(drawable: BitmapDrawable?) {
                    if (mImageView != null && drawable != null) {
                        mImageView.setImageDrawable(drawable)
                    }
                }

                /**
                 * 建立HTTP请求,并获取Bitmap对象。
                 *
                 * @param imageUrl 图片的URL地址
                 * @return 解析后的Bitmap对象
                 */
                private fun downloadBitmap(imageUrl: String): Bitmap? {
                    var bitmap: Bitmap? = null
                    var con: HttpURLConnection? = null
                    try {
                        val url = URL(imageUrl)
                        con = url.openConnection() as HttpURLConnection
                        con.connectTimeout = 5 * 1000
                        con.readTimeout = 10 * 1000
                        bitmap = BitmapFactory.decodeStream(con.inputStream)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    } finally {
                        con?.disconnect()
                    }
                    return bitmap
                }

            }

 先得到URL(我的是假数据),然后从缓存获取对应的图片,如果为空,就用上面的类重新下载

                 var url: String = imgData.get(Random().nextInt(imgData.size))
                val drawable = lruCache?.get(url)
                if (drawable != null) {
                    holder.iv_pic.setImageDrawable(drawable)
                } else {
                    val task: BitmapWorkerTask = BitmapWorkerTask(holder.iv_pic);
                    task.execute(url);
                }

如果使用okhttp,下载代码还可以这样写

首先一个网络连接类

import java.io.InputStream;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpUtils {
    public static InputStream getInputStrem(String url) {
        OkHttpClient client = new OkHttpClient();
        //2. 创建请求的Request 对象
        Request request = new Request.Builder()
                .url(url)
                .build();

        //3. 在Okhttp中创建Call 对象,将request和Client进行绑定
        //4. 执行Call对象(call 是interface 实际执行的是RealCall)中的`execute`方法
        try {
            Response response = client.newCall(request).execute();
            return response.body().byteStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

异步类(之前的下载类)

  inner class BitmapWorkerTask(private val mImageView: ImageView?) : AsyncTask() {

                override fun doInBackground(vararg params: String): BitmapDrawable {
                    val imageUrl = params[0]
                    // 在后台开始下载图片
                    val bitmap = downloadBitmap(imageUrl)
                    val drawable = BitmapDrawable(App.getContext().resources, bitmap)
                    addBitmapToMemoryCache(imageUrl, drawable)
                    return drawable
                }

                override fun onPostExecute(drawable: BitmapDrawable?) {
                    if (mImageView != null && drawable != null) {
                        mImageView.setImageDrawable(drawable)
                    }
                }

                /**
                 * 建立HTTP请求,并获取Bitmap对象。
                 *
                 * @param imageUrl 图片的URL地址
                 * @return 解析后的Bitmap对象
                 */
                private fun downloadBitmap(imageUrl: String): Bitmap? {
                    return BitmapFactory.decodeStream(OkHttpUtils.getInputStrem(imageUrl))
                }

            }

 

你可能感兴趣的:(RecyclerView加载图片)