Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自訂 TextView 元件:讓圖片與文字交錯排列

編輯:關於 Android 程式設計

新聞、文章、簡訊內容常常需要「一張圖 + 一段文字 + 再一張圖」這樣交錯呈現。系統的 TextView 雖然支援 Html.fromHtml() 搭配 <img> 標籤,但要控制每張圖的尺寸、對齊與非同步載入就顯得綁手。這一題可以用自訂 View 解決:讓一個元件同時吃「圖片」與「文字」兩種內容,依序排列出來。

技術要點

  1. 建立 attrs.xml,宣告自訂屬性、型別與樣式。
  2. 用 android.content.res.TypedArray 讀取這些屬性:
    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.customTextView);
  3. 版面檔中要先宣告自訂命名空間,再用完整類別名稱當標籤:
    xmlns:custom="https://schemas.android.com/apk/res/com.custom.textview"
    <com.custom.textview.CustomTextView ... />
  4. 用一個 HashMap 清單描述內容序列:key 是型別(image / text),value 是內容(圖片網址或文字)。
  5. 用 LinearLayout.LayoutParams 依內容型別動態設定每個子元件的版面參數。

AndroidManifest.xml

<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.custom.textview"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

因為要載入網路圖片,INTERNET 權限是必須的。

attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="customTextView">
        <attr name="image_width" format="dimension" />
        <attr name="image_height" format="dimension" />
        <attr name="text_color" format="color" />
        <attr name="text_size" format="dimension" />
    </declare-styleable>
</resources>

main.xml

<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:custom="https://schemas.android.com/apk/res/com.custom.textview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@android:color/white" >

    <com.custom.textview.CustomTextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        custom:image_width="200dp"
        custom:image_height="50dp" />

</LinearLayout>

CustomTextView.java

這個自訂元件繼承 LinearLayout(垂直排列),在 setText() 中依序走訪資料清單,遇到 image 就建立 ImageView 並啟動背景執行緒下載,遇到 text 就建立 TextView。

package com.custom.textview;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.Html;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class CustomTextView extends LinearLayout {
    private Context context;
    private TypedArray typedArray;
    private LayoutParams params;

    public CustomTextView(Context context) {
        super(context);
    }

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        this.setOrientation(LinearLayout.VERTICAL);
        // 從 attrs.xml 取得自訂屬性
        typedArray = context.obtainStyledAttributes(attrs, R.styleable.customTextView);
    }

    public void setText(ArrayList<HashMap<String, String>> data) {
        for (HashMap<String, String> hashMap : data) {
            String type = hashMap.get("type");
            String value = hashMap.get("value");

            if (type.equals("image")) {
                int imageWidth = typedArray.getDimensionPixelOffset(R.styleable.customTextView_image_width, 100);
                int imageHeight = typedArray.getDimensionPixelOffset(R.styleable.customTextView_image_height, 100);

                ImageView imageView = new ImageView(context);
                params = new LayoutParams(imageWidth, imageHeight);
                params.gravity = Gravity.CENTER_HORIZONTAL;
                imageView.setLayoutParams(params);
                imageView.setImageResource(R.drawable.ic_launcher);  // 先放佔位圖
                addView(imageView);

                // 背景執行緒非同步載入圖片
                new DownloadWork(value, imageView).start();

            } else if (type.equals("text")) {
                int textColor = typedArray.getColor(R.styleable.customTextView_text_color, 0xFF0000FF);
                float textSize = typedArray.getDimension(R.styleable.customTextView_text_size, 16);

                TextView textView = new TextView(context);
                textView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
                textView.setText(Html.fromHtml(value));
                textView.setTextColor(textColor);
                textView.setTextSize(textSize);
                addView(textView);
            }
        }
    }

    private class DownloadWork extends Thread {
        private String imageUrl;
        private ImageView imageView;

        public DownloadWork(String imageUrl, ImageView imageView) {
            this.imageUrl = imageUrl;
            this.imageView = imageView;
        }

        @Override
        public void run() {
            URL url = null;
            Drawable drawable = null;
            int newImageWidth = 0;
            int newImageHeight = 0;
            try {
                url = new URL(imageUrl);
                drawable = Drawable.createFromStream(url.openStream(), "image");
                newImageWidth = drawable.getIntrinsicWidth() / 3;
                newImageHeight = drawable.getIntrinsicHeight() / 3;
            } catch (Exception e) {
                e.printStackTrace();
            }
            SystemClock.sleep(2000);

            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("imageView", imageView);
            map.put("drawable", drawable);
            Message msg = handler.obtainMessage();
            msg.obj = map;
            msg.arg1 = newImageWidth;
            msg.arg2 = newImageHeight;
            handler.sendMessage(msg);
        }
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            @SuppressWarnings("unchecked")
            HashMap<String, Object> map = (HashMap<String, Object>) msg.obj;
            ImageView imageView = (ImageView) map.get("imageView");
            LayoutParams params = new LayoutParams(msg.arg1, msg.arg2);
            params.gravity = Gravity.CENTER_HORIZONTAL;
            imageView.setLayoutParams(params);
            Drawable drawable = (Drawable) map.get("drawable");
            imageView.setImageDrawable(drawable);
        }
    };
}

MainActivity.java

package com.custom.textview;

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

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    private final String text = " <p> 今年浙江衛視憑《中國好聲音》一舉做大"
            + ",其巨大的影響力直接波及到了各家衛視“跨年晚會”的戰略部署。日前"
            + ",“跨年晚會”概念的鼻祖湖南衛視率先表示“退出跨年燒錢大戰”。"
            + "但據湖南衛視內部人士透露,即使如此,今年的湖南跨年晚會也將會掂出“跨年季”這個概念"
            + ",“也就是從12月27日到12月31日,連續五天,我們將相繼用《百變大咖秀》、《快樂大本營》"
            + "、《女人如歌》、《天天向上》的特別節目來連續打造這個”季“的概念,直到12月31日的那場晚會。”</p>";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // 組裝要顯示的內容序列
        ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();

        HashMap<String, String> part1 = new HashMap<String, String>();
        part1.put("type", "image");
        part1.put("value", "https://www.linuxidc.com/upload/2012_12/121218101020341.png");

        HashMap<String, String> part2 = new HashMap<String, String>();
        part2.put("type", "text");
        part2.put("value", text);

        HashMap<String, String> part3 = new HashMap<String, String>();
        part3.put("type", "image");
        part3.put("value", "https://www.linuxidc.com/upload/2012_12/121218101020341.png");

        data.add(part1);
        data.add(part2);
        data.add(part3);

        CustomTextView customTextView = (CustomTextView) findViewById(R.id.textView);
        customTextView.setText(data);
    }
}

這份範例可以怎麼改進

  • 圖片縮放寫死除以 3。 實務上應依 ImageView 的實際尺寸計算比例,並用 BitmapFactory.Options.inSampleSize 做降採樣,避免大圖直接載入造成 OOM。
  • 沒有快取。 每個 ImageView 都重新下載一次,清單滾動時成本很高,正式專案該加上記憶體與磁碟快取。
  • SystemClock.sleep(2000) 只是為了看得到佔位圖效果,實作時請移除。
  • 非同步更新 UI 一律走 Handler。 背景執行緒不能直接操作 View,範例用 Message 把 Drawable 與尺寸帶回主執行緒再設定,這個原則在任何版本都適用。
  • 若只是要「圖文混排」,也可以考慮直接繼承 TextView 並用 Html.ImageGetter 實作圖片載入,程式碼量會少很多。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved