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

讓自定義 TextView 的 drawableLeft 與文本一起居中

編輯:關於 Android 程式設計

TextView 的 drawableLeft、drawableRight、drawableTop 這幾個屬性非常好用,能在文本的四周擺放圖片而無需嵌套額外布局。但它有個惱人的限制:drawableLeft 無法與文本作為一個整體居中,單純設置 gravity="center" 並不奏效。本文通過一個自定義控件解決這個問題。

效果預覽

自定義控件

核心思路是在 onDraw 之前,先算出「文本寬度 + 圖片寬度 + 二者間距」的總寬度,再把畫布水平平移,讓這一整塊內容居中:

 public class DrawableCenterTextView extends TextView { public DrawableCenterTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public DrawableCenterTextView(Context context, AttributeSet attrs) { super(context, attrs); } public DrawableCenterTextView(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { Drawable[] drawables = getCompoundDrawables(); if (drawables != null) { Drawable drawableLeft = drawables[0]; if (drawableLeft != null) { float textWidth = getPaint().measureText(getText().toString()); int drawablePadding = getCompoundDrawablePadding(); int drawableWidth = 0; drawableWidth = drawableLeft.getIntrinsicWidth(); float bodyWidth = textWidth + drawableWidth + drawablePadding; canvas.translate((getWidth() - bodyWidth) / 2, 0); } } super.onDraw(canvas); } }

總結

這個自定義控件用法與普通 TextView 完全一致,無需新增任何屬性,直接寫在布局裡即可。需要注意的是,目前只處理了 drawableLeft 的居中,drawableRight 暫不支持。以上就是解決 drawableLeft 與文本一起居中的完整方案,需要的朋友可以參考。

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