【Android 自定义控件】TextView的drawable与text一起居中

解决的问题:drawableleft,drawableright,drawabletop,drawablebottom与text一起gravity="center"居中的问题。


自定义一个TextView控件,叫做:DrawableCenterTextView.java


package com.dzq.smswclient.widget;

/**
 * Data:2016-05-26 16:30
 * Created by YJG
 */

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * drawableTop与文本一起居中显示
 * com.yjg.myapplication2.widget.DrawableCenterTextView
 */
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 drawableTop = drawables[1];
            for (int i = 0; i < drawables.length; i++) {
                Drawable drawable = drawables[i];
                if (drawable != null) {
                    if (i == 0 || i==3) {
                        //drawableLeft or drawableRight with singline text four word ()
//                        float textWidth = getPaint().measureText(getText().toString());
                        float textWidth = getPaint().measureText("正正正正");
                        int drawablePadding = getCompoundDrawablePadding();
                        int drawableWidth = 0;
                        drawableWidth = drawable.getIntrinsicWidth();
                        float bodyWidth = textWidth + drawableWidth + drawablePadding;
                        canvas.translate((getWidth() - bodyWidth) / 2, 0);
                    } else if (i == 1 || i==4) {
                        //drawableTop or drawableBottom
                        float textHeight = getPaint().measureText("正");
                        int drawablePadding = getCompoundDrawablePadding();
                        int drawableHeight = drawableTop.getIntrinsicHeight();
                        float bodyWidth = textHeight + drawableHeight + drawablePadding;
                        canvas.translate(0, (getHeight() - bodyWidth) / 2);
                    }
                }
            }
        }
        super.onDraw(canvas);
    }
}

注:上面代码可以看到,用“正”来给文本宽度,这里可以根据需要调整“正”的个数


具体使用:(其中一行)

drawableLeft或者drawableRight与text




            
            
        

style.xml样式


    

再如:

drawabletop,drawablebottom与text

图示:

【Android 自定义控件】TextView的drawable与text一起居中_第1张图片


 
            
            
        

style.xml










你可能感兴趣的:(android,自定义控件)