編輯:Android 開發實例
做內容型 App 時常會遇到這種版面:一張圖片靠左(或靠右),文字繞著它排;圖片下方的文字還要跟右側的文字連貫起來,讀起來像同一段話。這件事 TextView 本身做不到,得自己算。
目標成果如下圖:

把整段文字切成兩塊,分別放進兩個 TextView:
setPadding() 把頂部撐開圖片的高度,讓文字從圖片底部才開始。關鍵是算出「右側那一塊到底放得下幾個字」,而這個數字不能靠猜,必須量。
因為邏輯不算複雜,示範直接寫在 Activity 裡:
package com.example.test; import android.app.Activity; import android.graphics.Paint; import android.os.Bundle; import android.view.ViewTreeObserver; import android.widget.ImageView; import android.widget.TextView; public class MainActivity extends Activity { boolean imageMeasured = false; TextView tv_right; TextView tv_bottom; static final String text = "葉凡:小說主角,與眾老同學在泰山聚會時一同被九龍拉棺帶離地球," + "進入北斗星域,得知自己是荒古聖葉凡 葉凡體。歷險禁地,習得源術,斗聖地世家,戰太古生物," + "重組天庭,葉凡輾轉四方得到許多際遇和挑戰,功力激增,眼界也漸漸開闊。一個浩大的仙俠世界," + "就以他的視角在讀者面前展開。姬紫月:姬家小姐,出場年齡十七歲。被葉凡劫持一同經歷青銅古殿歷險," + "依靠碎裂的神光遁符解除禁制,反過來挾持葉凡一同進入太玄派尋找秘術。" + "在葉凡逃離太玄後姬紫月在孔雀王之亂中被華雲飛追殺,又與葉凡[2]相遇,被葉凡護送回姬家" + ",漸漸對葉凡產生微妙感情。後成為葉凡的妻子,千載後於飛仙星成仙,在葉凡也進入仙路後再見龐博:" + "葉凡大學時最好的朋友,壯碩魁偉,直率義氣。到達北斗星域後因服用了聖果被靈墟洞天作為仙苗," + "在青帝墳墓處為青帝十九代孫附體離去,肉身被錘煉至四極境界。後葉凡與黑皇鎮壓老妖神識," + "龐博重新掌控自己身軀,取得妖帝古經和老妖本體祭煉成的青蓮法寶,習得妖帝九斬和天妖八式," + "但仍偽裝成老妖留在妖族。出關後找上葉凡,多次與他共進退。星空古路開啟後由此離開北斗," + "被葉凡從妖皇墓中救出,得葉凡授予者字秘、一氣化三清,與葉凡同闖試煉古路,一起建設天庭"; // 屏幕的高度 int screenWidth = 0; // 總共可以放多少個字 int count = 0; // textView全部字符的寬度 float textTotalWidth = 0.0f; // textView一個字的寬度 float textWidth = 0.0f; Paint paint = new Paint(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_right = (TextView) findViewById(R.id.test_tv_right); tv_bottom = (TextView) findViewById(R.id.test_tv_bottom); final ImageView imageView = (ImageView) findViewById(R.id.test_image); imageView.setImageResource(R.drawable.ee); screenWidth = getWindowManager().getDefaultDisplay().getWidth(); /** * 獲取一個字的寬度 */ textWidth = tv_right.getTextSize(); paint.setTextSize(textWidth); /** * 因為圖片一開始的時候,高度是測量不出來的,通過增加一個監聽器,即可獲取其圖片的高度和長度 */ ViewTreeObserver vto = imageView.getViewTreeObserver(); vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { public boolean onPreDraw() { if (!imageMeasured) { imageMeasured = true; int height = imageView.getMeasuredHeight(); int width = imageView.getMeasuredWidth(); drawImageViewDone(width, height); } return imageMeasured; } }); } private void drawImageViewDone(int width, int height) { // 一行字體的高度 int lineHeight = tv_right.getLineHeight(); // 可以放多少行 int lineCount = (int) Math.ceil((double) height / (double) lineHeight); // 一行的寬度 float rowWidth = screenWidth - width - tv_right.getPaddingLeft() - tv_right.getPaddingRight(); // 一行可以放多少個字 int columnCount = (int) (rowWidth / textWidth); // 總共字體數等於 行數*每行個數 count = lineCount * columnCount; // 一個TextView中所有字符串的寬度和(字體數*每個字的寬度) textTotalWidth = (float) ((float) count * textWidth); measureText(); tv_right.setText(text.substring(0, count)); // 檢查行數是否大於設定的行數,如果大於的話,就每次減少一個字符,重新計算行數與設定的一致 while (tv_right.getLineCount() > lineCount) { count -= 1; tv_right.setText(text.substring(0, count)); } tv_bottom.setPadding(0, lineCount * lineHeight - height, 0, 0); tv_bottom.setText(text.substring(count)); } /** * 測量已經填充的長度,計算其剩下的長度 */ private void measureText() { String string = text.substring(0, count); float size = paint.measureText(string); int remainCount = (int) ((textTotalWidth - size) / textWidth); if (remainCount > 0) { count += remainCount; measureText(); } } }
版面檔:
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" > <ImageView android:id="@+id/test_image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:scaleType="fitXY" /> <TextView android:id="@+id/test_tv_right" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_toRightOf="@id/test_image" android:gravity="fill_horizontal" android:paddingLeft="7dp" android:textSize="16sp" /> <TextView android:id="@+id/test_tv_bottom" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/test_image" android:gravity="fill_horizontal" android:textSize="16sp" /> </RelativeLayout> </ScrollView>
圖片尺寸必須先量出來。版面尚未完成時呼叫 getMeasuredHeight() 會得到 0。範例用 ViewTreeObserver.OnPreDrawListener 等待測量完成,這個思路正確;不過更現代的替代是 View.doOnPreDraw { }(Core KTX)或直接改用 ViewBinding 搭配 post { }。
中文字寬不等於 textSize。範例用 getTextSize() 當作單字寬度,對全形中文剛好接近,但一旦文字裡混有英文、數字或全形標點,誤差就會累積。更準的做法是 paint.measureText() 逐字量,或以 StaticLayout 直接排版後量高度。
setText 後立刻測量結果不準。這是最實用的一條經驗:因為 setText() 之後 TextView 尚未完成重新測量與繪製,此時讀 getLineCount() 拿到的可能是舊值。解法是在 setText() 後用 postDelayed() 延遲約 50 毫秒再量,或者用 ViewTreeObserver 等待下一輪 layout 通過。
遞迴補字要小心效能。measureText() 採取遞迴補足剩餘空間,字數多時會呼叫好幾層。改寫成 while 迴圈會更親民,也不必有堆疊顧慮。
為什麼不用更簡單的方案?如果目標 SDK 允許,Android 8.0(API 26)之後有 LetterSpacing 與 JustificationMode,而 Compose 的 RichText/FlowRow 這類排版能力也越來越成熟。另外,若圖片與文字是「文章內容」而非「版面裝飾」,用 WebView 渲染 HTML(float/shape-outside)往往比手算更省事、也更準。
手算這條路仍有它的價值:完全自控、沒有額外依賴、在舊版本上也能跑。但記得把「延遲測量」與「字寬不固定」這兩個坑填好,成果才會穩定。
Android手機衛士(十九):建立首次密碼設定畫面
本篇要完成的是手機衛士中「第一次設定密碼」的流程。當使用者首次進入手機防盜功能時,必須先建立一組密碼,後續才能進行驗證與保護。畫面配置這個頁面可以採用垂直 LinearL
Android JSON 剖析教學:JSONObject 與天氣資料
在 Android 開發中,JSON 解析是取得遠端資料的關鍵步驟。相較於 XML,JSON 更精簡,也更容易與 Web API 搭配。 先找出需要的欄位 解析前,先確認
Android 自訂 ActionBar 的實作方式
自訂 ActionBar 的概念 在 Android 3.0 之前,若需要類似 ActionBar 的頂部操作列,可自訂元件或使用開源方案。這類元件通常包含標題、首頁圖示
Java 開發環境建置(二):寫出第一個 Hello World
JDK 裝好之後,用一支最經典的程式確認環境可用。建立一個名為 hello.java 的檔案: public class hello { public stat