Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android rotate TextView in API Level >= 8

I have simple TextView

<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:rotation="45"
   android:text="Simple text" />

The text wont be rotated to 45 degree on Android 2.2.2.

I saw different threads, but everybody is doing an animation. I don't want to animate. All I want is to rotate the textview.

like image 518
Zbarcea Christian Avatar asked Nov 07 '13 10:11

Zbarcea Christian


2 Answers

In android for any new view there is a method called setRotation(float) you can use it

textview.setRotation(float);

but please note that this method is Added in API level 11

so if you want to support it you can use this

if (Build.VERSION.SDK_INT < 11) {

    RotateAnimation animation = new RotateAnimation(oldAngel, newAngel);
    animation.setDuration(100);
    animation.setFillAfter(true);
    textview.startAnimation(animation);
} else {

    textview.setRotation(progress);
}
like image 150
Simon K. Gerges Avatar answered Sep 28 '22 17:09

Simon K. Gerges


Create a custom TextView like this

public class VerticalTextView extends TextView{
   final boolean topDown;

   public VerticalTextView(Context context, AttributeSet attrs){
      super(context, attrs);
      final int gravity = getGravity();
      if(Gravity.isVertical(gravity) && (gravity&Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
         setGravity((gravity&Gravity.HORIZONTAL_GRAVITY_MASK) | Gravity.TOP);
         topDown = false;
      }else
         topDown = true;
   }

   @Override
   protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
      super.onMeasure(heightMeasureSpec, widthMeasureSpec);
      setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
   }

   @Override
   protected boolean setFrame(int l, int t, int r, int b){
      return super.setFrame(l, t, l+(b-t), t+(r-l));
   }

   @Override
   public void draw(Canvas canvas){
      if(topDown){
         canvas.translate(getHeight(), 0);
         canvas.rotate(90);
      }else {
         canvas.translate(0, getWidth());
         canvas.rotate(-90);
      }
      canvas.clipRect(0, 0, getWidth(), getHeight(), android.graphics.Region.Op.REPLACE);
      super.draw(canvas);
   }
}

and use canvas.rotate(90) where 90 is the rotating angle.

like image 40
Jitender Dev Avatar answered Sep 28 '22 15:09

Jitender Dev