編輯:關於 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 與文本一起居中的完整方案,需要的朋友可以參考。
Android 實現帶磁性的懸浮窗效果
本文示範如何實現一個「帶磁性」的懸浮窗,效果類似 360 的那個綠色小人。它主要具備三個特性:懸浮在所有窗體之上、能吸附於螢幕邊緣、並支援點擊。以下把這三點封裝成一個 F
Android 圖片開發內幕(一):Bitmap 內存計算與 OOM 防範基礎
前言:原本我做的是 TV 應用,因為公司要出手機產品、人手緊張,就被抽調去支援——誰讓我是「雷鋒」呢。當時負責的模塊是處理手機裡的應用 ICON,做美化、與底板合成裁剪,
Android 自定義 View:Bitmap 繪圖與塗鴉保存完整教學
本篇文章以 Bitmap 作為自定義 View 的繪圖基礎,示範如何把圖片畫到底層、加上蒙版,並讓手指塗鴉區域變透明。 三步驟 第一步,將背景 Bitmap 透過 dr
讀書筆記:Android LayoutInflater.inflate 參數與源碼解析
LayoutInflater 是 Android 將 XML 版面轉成 View 物件的核心類別。本文從取得實例、inflate 多載關係,到 attachToRoot