怎么办呢,可以用TextView和ImageView组合。而这里我们可以自定义控件,重写TextView的onDraw方法,重新绘制就可以了。
要使得drawableRight和文本紧挨着就只能设置gravity为Gravity.RIGHT了,然后要让他们居中就在onDraw时将画布平移至合适的位置。效果如下
image.png
代码:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.support.v7.widget.AppCompatTextView;
/**
* 文字和drawableRight一起居中的TextView
*
*/
public class RightDrawableCenterTextView extends AppCompatTextView {
public RightDrawableCenterTextView(Context context) {
this(context, null);
}
public RightDrawableCenterTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RightDrawableCenterTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setGravity(Gravity.CENTER | Gravity.RIGHT);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable[] drawables = getCompoundDrawables();
Drawable drawable = drawables[2];
if (drawable != null) {
float textWidth = getPaint().measureText(getText().toString());
int drawablePadding = getCompoundDrawablePadding();
int drawableWidth = drawable.getMinimumWidth();
float bodyWidth = textWidth + drawableWidth + drawablePadding + getPaddingLeft() + getPaddingRight();
canvas.translate((bodyWidth - getWidth()) / 2, 0);
}
super.onDraw(canvas);
}
}
网友评论