Android 讓自定義TextView的drawableLeft與文本一起居中
前言
TextView的drawableLeft、drawableRight和drawableTop是一個常用、好用的屬性,可以在文本的上下左右放置一個圖片,而不使用更加復(fù)雜布局就能達到,我也常常喜歡用RadioButton的這幾個屬性實現(xiàn)很多效果,但是苦于不支持讓drawbleLeft與文本一起居中,設(shè)置gravity為center也無濟于事,終于有空研究了一下,這里與大家一起分享。
正文
一、效果圖

二、實現(xiàn)代碼
自定義控件
/**
* drawableLeft與文本一起居中顯示
*
*
*/
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);
}
}
總結(jié):和普通TextView用法一致,無需額外增加屬性,drawableRight不能用。
以上就是對自定義控件讓TextView的drawableLeft與文本一起居中顯示的問題解決,需要的朋友可以參考下。
相關(guān)文章
android不同activity之間共享數(shù)據(jù)解決方法
最近做局域網(wǎng)socket連接問題,要在多個activity之間公用一個socket連接,就在網(wǎng)上搜了下資料,感覺還是application方法好用,帖出來需要的朋友可以參考下2012-11-11

