You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中Bitmap适配器创建及ImageView显示问题求助

解决方案

一、修正图片下载代码

原代码存在变量名不一致、主线程处理解码操作的问题,以下是修正后的版本:

private fun downloadImage(item: Item) = Thread {
    var imageConnection: HttpURLConnection? = null
    try {
        val url = URL(item.url)
        imageConnection = url.openConnection() as HttpURLConnection
        if (imageConnection.responseCode == HttpURLConnection.HTTP_OK) {
            // 子线程解码图片,避免阻塞主线程
            val bitmap = BitmapFactory.decodeStream(imageConnection.inputStream)
            runOnUiThread {
                // 将Bitmap加入数据源并通知适配器更新
                imageList.add(bitmap)
                imageAdapter.notifyDataSetChanged()
            }
        } else {
            runOnUiThread {
                Toast.makeText(this, "下载失败!", Toast.LENGTH_SHORT).show()
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
        runOnUiThread {
            Toast.makeText(this, "下载出错:${e.message}", Toast.LENGTH_SHORT).show()
        }
    } finally {
        imageConnection?.disconnect()
    }
}.start()

二、创建适配Bitmap的适配器

系统没有现成的纯ImageView布局,需要自定义布局后编写适配器:

1. 自定义列表项布局

在res/layout目录下创建item_image.xml:

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/item_image_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:scaleType="centerCrop"/>

2. ListView适配的ArrayAdapter

修正原适配器的变量错误、布局错误及方法调用问题:

class ImageAdapter(
    private val context: Context,
    private val imageList: MutableList<Bitmap>
) : ArrayAdapter<Bitmap>(context, R.layout.item_image, imageList) {

    private data class ImageHolder(val imageView: ImageView)

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view = convertView ?: LayoutInflater.from(context)
            .inflate(R.layout.item_image, parent, false)
            .apply {
                tag = ImageHolder(findViewById(R.id.item_image_view))
            }

        val holder = view.tag as ImageHolder
        holder.imageView.setImageBitmap(imageList[position])

        return view
    }
}

3. 推荐:RecyclerView适配器(性能更优)

如果用RecyclerView,适配器代码如下:

class ImageRecyclerAdapter(private val imageList: List<Bitmap>) :
    RecyclerView.Adapter<ImageRecyclerAdapter.ImageViewHolder>() {

    class ImageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val imageView: ImageView = itemView.findViewById(R.id.item_image_view)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_image, parent, false)
        return ImageViewHolder(view)
    }

    override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
        holder.imageView.setImageBitmap(imageList[position])
    }

    override fun getItemCount() = imageList.size
}

三、显示图片

1. ListView显示方式

在Activity布局中添加ListView:

<ListView
    android:id="@+id/image_list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

在Activity中初始化:

private lateinit var imageList: MutableList<Bitmap>
private lateinit var imageAdapter: ImageAdapter

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    imageList = mutableListOf()
    imageAdapter = ImageAdapter(this, imageList)
    binding.imageListView.adapter = imageAdapter

    // 调用下载方法
    // downloadImage(yourItemInstance)
}

2. RecyclerView显示方式

在Activity布局中添加RecyclerView:

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

在Activity中初始化:

private lateinit var imageList: MutableList<Bitmap>
private lateinit var recyclerAdapter: ImageRecyclerAdapter

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    imageList = mutableListOf()
    recyclerAdapter = ImageRecyclerAdapter(imageList)
    binding.imageRecyclerView.apply {
        adapter = recyclerAdapter
        layoutManager = LinearLayoutManager(this@MainActivity)
    }

    // 调用下载方法
    // downloadImage(yourItemInstance)
}

必要配置

  • 网络权限:在AndroidManifest.xml中添加<uses-permission android:name="android.permission.INTERNET"/>
  • 明文HTTP支持(若使用HTTP链接):安卓9及以上需在res/xml创建network_security_config.xml,并在Manifest的application标签中添加android:networkSecurityConfig="@xml/network_security_config"

内容的提问来源于stack exchange,提问作者Begin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 12:17:04