Creating a Vertical Button View in Android


This post will explain you "How to create a vertical button in android?". In Android There is no predefined vertical button. we have to customize the button view.

VerticalButton

If the Target API is more then 11 you can use android:rotation="270" in xml. Otherwise you have to create a custom Button to achieve this vertical button.

VerticalButton.java


public class VerticalButton extends Button{
 final boolean topDown;
 public VerticalButton(Context context, AttributeSet attrs){
  super(context, attrs);
  final int gravity = getGravity();
  if(Gravity.isVertical(gravity) && (gravity&Gravity.VERTICALGRAVITYMASK) == Gravity.BOTTOM) {
   setGravity((gravity&Gravity.HORIZONTALGRAVITYMASK) | Gravity.TOP);
   topDown = true;
  }else
   topDown = false;
 }
 @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();
  if(topDown){
   canvas.translate(getWidth(), 0);
   canvas.rotate(90);
  }else {
   canvas.translate(0, getHeight());
   canvas.rotate(-90);
  }
canvas.translate(getCompoundPaddingLeft(),getExtendedPaddingTop());
getLayout().draw(canvas);
canvas.restore();
}
}