2

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.

enter image description here

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.

enter image description here

I tried Relative Layout with Button and TextView but I couldn't bring the TextView over the Button

Thanks in advance.

Emil Mammadov
  • 380
  • 4
  • 20

3 Answers3

1

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();
}
Emil Mammadov
  • 380
  • 4
  • 20
0

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

zulu_papa
  • 415
  • 6
  • 12
0

all you have to do is set button text as "E\nN\nT\nE\nR"

Kdon Patel
  • 107
  • 1
  • 15