很多控件(比如TextView/Button...)可以使用drawableLeft/drawableRight等,但是使用的时候发现文本和图片总是不能一起居中显示,所以下面提供一种解决方案,这里以Button/drawable Left为例:
使用步骤:
- 自定义Button
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
/**
* Created by Administrator on 2017/4/8.
*/
/**
* drawableRight与文本一起居中显示
*
*
*/
class DrawableLeftCenterButton extends android.support.v7.widget.AppCompatButton {
public DrawableLeftCenterButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
canvas = getTopCanvas(canvas);
super.onDraw(canvas);
}
private Canvas getTopCanvas(Canvas canvas) {
Drawable[] drawables = getCompoundDrawables();
if (drawables == null) {
return canvas;
}
Drawable drawable = drawables[0];// 左面的drawable
if (drawable == null) {
drawable = drawables[2];// 右面的drawable
}
// float textSize = getPaint().getTextSize(); // 使用这个会导致文字竖向排下来
float textSize = getPaint().measureText(getText().toString());
int drawWidth = drawable.getIntrinsicWidth();
int drawPadding = getCompoundDrawablePadding();
float contentWidth = textSize + drawWidth + drawPadding;
int leftPadding = (int) (getWidth() - contentWidth);
setPadding(0, 0, leftPadding, 0); // 直接贴到左边
float dx = (getWidth() - contentWidth) / 2;
canvas.translate(dx, 0);// 往右移动
return canvas;
}
}
- 在布局文件中使用:
和普通button一样使用
<com.view.DrawableLeftCenterButton
android:id="@+id/btu_control_order"
android:layout_width="0dp"
android:layout_height="@dimen/x86"
android:layout_weight="1"
android:background="@drawable/btu_shape"
android:drawableLeft="@mipmap/control_icon"
android:includeFontPadding="false"
android:text="@string/control" />