Reputation: 468
I want to rotate the text on the button, but I could not do it all day.
I tried Custom Vertical Button but it is not centering the text in the button. I tried all gravity options in java and xml code.
Here is my VerticalButton code:
public class VerticalButton extends Button{
public VerticalButton(Context context, AttributeSet attrs){
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(heightMeasureSpec, widthMeasureSpec);
setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
}
@Override
protected void onDraw(Canvas canvas){
TextPaint textPaint = getPaint();
textPaint.setColor(getCurrentTextColor());
textPaint.drawableState = getDrawableState();
canvas.save();
canvas.translate(0, getHeight());
canvas.rotate(-90);
canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop());
getLayout().draw(canvas);
canvas.restore();
}
}
I tried rotate Button with android:rotation="-90"
That didn't work the way I wanted. Because it is not editing the background size.
I tried Relative Layout with Button and TextView but I couldn't bring the TextView over the Button
Thanks in advance.
Upvotes: 2
Views: 1010
Reputation: 468
I found a solution.
I edited the onDraw function. Firstly get width and height of text with getTextBounds()
In getTextBounds()
give the the text of your Button as parameter.
And edit the canvas.translate()
function like below. And it is centering the text in the button.
@Override
protected void onDraw(Canvas canvas) {
TextPaint textPaint = getPaint();
textPaint.setColor(getCurrentTextColor());
textPaint.drawableState = getDrawableState();
Rect bounds = new Rect();
textPaint.getTextBounds("ENTER",0,"ENTER".length(), bounds);
Log.e("TAG", "onDraw: "+ bounds.width() + " "+bounds.height());
canvas.save();
canvas.translate(getWidth()/2 - bounds.height(), (float) (getHeight()/2 + bounds.width()/1.5));
canvas.rotate(-90);
getLayout().draw(canvas);
canvas.restore();
}
Upvotes: 1
Reputation: 415
try one of these two:
Is it possible to write vertically in a textview in android?
Sideways View with XML Android
Allegedly, you can set the rotation property in xml, like in last one and it may work. I didn't try it out, hope you will find success with this. Since you tried with -90, try setting an degree to 270
Upvotes: 0