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

TextView 寬度填滿時 Drawable 無法居中?自定義繪製解法

編輯:關於 Android 程式設計

當 TextView 寬度設為 match_parent 或 weight,又搭配 gravity center 時,DrawableLeft 等圖示可能無法與文字一起置中。

一種解法是自訂 TextView,在 onDraw 中自行計算文字與 Drawable 的總寬度,再決定繪製起點。如此即使檢視本身佔滿寬度,也能讓圖文整體居中。

另一種較輕量的做法,是保留系統 Drawable,但在繪製前用 canvas.translate 把內容往中間補償。兩種方式各有取捨,前者彈性高,後者程式碼較短。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved