萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android Handler 實現圖文混排列表:AsyncTask 取數 + Handler 異步載圖 + BaseAdapter 綁定

架構概覽

  1. AsyncTask:主線程發起 → 背景執行緒請求 JSON → 解析 → onPostExecute 交給 Adapter。
  2. Handler + 背景執行緒:Adapter getView 中啟動下載執行緒 → 解碼 Bitmap → Handler.obtainMessage() 送回主線程 → handleMessage 更新 ImageView。
  3. BaseAdapter:持有資料列表,實現 getView 視圖復用 (ViewHolder 模式)。

1. 資料模型與常數

// 伺服器回傳 JSON 範例
// [{"imageName":"image1.png","name":"蘋果","price":12}, ...]

data class Product(
    val imageName: String,
    val name: String,
    val price: Int
)

// 統一管理 URL
object Api {
    const val BASE = "https://192.168.1.102:1231/json/"
    const val PRODUCT_LIST = "${BASE}returnCommondityJson.ashx"
    const val IMAGE_BASE = "${BASE}img/"
}

2. AsyncTask 取得商品列表

private class FetchProductsTask : AsyncTask>() {
    private val dialog = ProgressDialog(this@MainActivity).apply {
        setTitle("載入中"); setMessage("請稍候..."); setCancelable(false)
    }

    override fun onPreExecute() { dialog.show() }

    override fun doInBackground(vararg params: String): List {
        val url = params[0]
        return try {
            val client = OkHttpClient()
            val request = Request.Builder().url(url).build()
            client.newCall(request).execute().use { response ->
                if (!response.isSuccessful) throw IOException("HTTP ${response.code}")
                val json = response.body?.string() ?: "[]"
                Gson().fromJson(json, object : TypeToken>() {}.type)
            }
        } catch (e: Exception) {
            Log.e("FetchProducts", "失敗", e)
            emptyList()
        }
    }

    override fun onPostExecute(result: List) {
        dialog.dismiss()
        adapter.submitList(result) // 使用 ListAdapter 或手動 notifyDataSetChanged
    }
}

3. 異步載圖工具類 (Handler 版)

class ImageLoader(private val handler: Handler) {
    interface Callback { fun onImageLoaded(drawable: Drawable?) }

    fun loadImage(imageUrl: String, callback: Callback) {
        Thread {
            try {
                val inputStream = URL(imageUrl).openStream()
                val drawable = Drawable.createFromStream(inputStream, null)
                val msg = handler.obtainMessage(1, drawable).apply { obj = callback }
                handler.sendMessage(msg)
            } catch (e: Exception) {
                Log.e("ImageLoader", "載入失敗 $imageUrl", e)
                handler.post { callback.onImageLoaded(null) }
            }
        }.start()
    }
}

// 在 Activity 建立 Handler
private val uiHandler = Handler(Looper.getMainLooper()) { msg ->
    if (msg.what == 1) {
        val callback = msg.obj as ImageLoader.Callback
        val drawable = msg.obj as? Drawable // 注意:這裡 obj 被複用,實際應用建議用 Bundle 或自訂 Message
        callback.onImageLoaded(drawable)
        true
    } else false
}

4. BaseAdapter 實現 (含 ViewHolder 與圖片載入)

class ProductAdapter : BaseAdapter() {
    private var data: List = emptyList()
    private val inflater: LayoutInflater
    private val imageLoader: ImageLoader

    constructor(context: Context) {
        inflater = LayoutInflater.from(context)
        imageLoader = ImageLoader(Handler(Looper.getMainLooper()))
    }

    fun submitList(newData: List) {
        data = newData
        notifyDataSetChanged()
    }

    override fun getCount() = data.size
    override fun getItem(pos: Int) = data[pos]
    override fun getItemId(pos: Int) = pos.toLong()

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view: View
        val holder: ViewHolder
        if (convertView == null) {
            view = inflater.inflate(R.layout.item_product, parent, false)
            holder = ViewHolder(view)
            view.tag = holder
        } else {
            view = convertView
            holder = view.tag as ViewHolder
        }

        val product = data[position]
        holder.name.text = product.name
        holder.price.text = "NT$ ${product.price}"
        holder.image.setImageResource(R.drawable.placeholder) // 佔位圖

        // 異步載圖,使用 tag 防止列表滑動時圖片錯位
        val imageUrl = Api.IMAGE_BASE + product.imageName
        holder.image.tag = imageUrl
        imageLoader.loadImage(imageUrl) { drawable ->
            if (holder.image.tag == imageUrl) { // 仍是同一項目
                holder.image.setImageDrawable(drawable)
            }
        }
        return view
    }

    class ViewHolder(view: View) {
        val name: TextView = view.findViewById(R.id.tv_name)
        val price: TextView = view.findViewById(R.id.tv_price)
        val image: ImageView = view.findViewById(R.id.iv_product)
    }
}

5. 佈局檔案

res/layout/item_product.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="16dp">

    <ImageView
        android:id="@+id/iv_product"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:scaleType="centerCrop" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginStart="16dp"
        android:orientation="vertical">

        <TextView android:id="@+id/tv_name" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:textSize="18sp" android:textStyle="bold" />
        <TextView android:id="@+id/tv_price" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:textSize="16sp" android:textColor="#E91E63" />
    </LinearLayout>
</LinearLayout>

關鍵優化點

  • ViewHolder 模式:避免重複 findViewById。
  • Tag 機制防錯位:holder.image.tag = url,回調時比對,避免列表快速滑動導致圖片閃爍錯亂。
  • 佔位圖:提升感知速度。
  • 記憶體快取:生產環境請接入 Glide / Coil / Picasso / Fresco,自動處理快取、生命週期、預取、解碼縮放。

現代寫法 (Kotlin + Coroutines + Coil)

// 佈局 XML 加入 Coil 的 AsyncImage
// 

// Adapter 簡化為
class ProductAdapter : ListAdapter(DiffCallback()) {
    override fun onCreateViewHolder(parent, viewType) = ProductViewHolder(
        LayoutInflater.from(parent.context).inflate(R.layout.item_product, parent, false))
    override fun onBindViewHolder(holder, position) = holder.bind(getItem(position))
}

class ProductViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    fun bind(p: Product) {
        itemView.tv_name.text = p.name
        itemView.tv_price.text = "NT$ ${p.price}"
        itemView.iv_product.load(Api.IMAGE_BASE + p.imageName) { // Coil 擴充函數
            crossfade(true)
            placeholder(R.drawable.placeholder)
            error(R.drawable.error)
        }
    }
}
copyright © 萬盛學電腦網 all rights reserved