【Android】自定義控件讓TextView的drawableLeft與文本一起居中顯示



前言

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

 

聲明

歡迎轉載,請注明出處!

博客園:http://www.cnblogs.com/

農民伯伯: http://www.cnblogs.com/over140/

 

正文

一、效果圖

 

二、實現代碼 

自定義控件

/**
 * drawableLeft與文本一起居中顯示
 * 
 * 
@author  農民伯伯
 * 
@see   http://www.cnblogs.com/over140/p/3464348.html
 * 
 
*/
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用法一致,無需額外增加屬性。

 

2013-12-13 注意,drawableRight不管用!感謝網友提醒,后續有進展了再更新文章。 

 

結束

那些讓你難受的技術問題一定要找時間想辦法擺平TA! 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM