Android rotate TextView in API Level >= 8

2019-02-08 19:07发布

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.

3条回答
干净又极端
2楼-- · 2019-02-08 19:30

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.

查看更多
ら.Afraid
3楼-- · 2019-02-08 19:41

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);
}
查看更多
太酷不给撩
4楼-- · 2019-02-08 19:45

I found "android:rotation" is not work in SDK 21,in other words is Android 5.0. But i just found this problem in layout preview, not test in really device.

查看更多
登录 后发表回答