2012-01-22 37 views
27

Estoy teniendo una situación en la página de gráficos donde LinearLayout debe mostrar el TextView con 90 grados de rotación.Cómo rotar TextView 90 grados y mostrar

+0

http://stackoverflow.com/questions/1258275/vertical-rotated-label-in-android comprobé esto y resolvió mi problema – sakshi

+0

Es posible hacer esto en XML a partir de API 11 (Android 3.0). http://stackoverflow.com/questions/3774770/sideways-view-with-xml-android – chobok

Respuesta

35

La forma más rápida y más conveniente es Rotate por Animation

animación uso rotarla en la Vista de Texto normal como tal.

rotateAnimation.xml:

<rotate xmlns:android="http://schemas.android.com/apk/res/android" 
      android:fromDegrees="0" 
      android:toDegrees="-90" 
      android:pivotX="50%" 
      android:duration="0" 
      android:fillAfter="true" /> 

Código Java:

TextView text = (TextView)findViewById(R.id.txtview);  
    text.setText("rotated text here"); 

    RotateAnimation rotate= (RotateAnimation)AnimationUtils.loadAnimation(this,R.anim.rotateAnimation); 
    text.setAnimation(rotate); 
+0

Esto es bueno, pero no me ayudó mucho comprobé este http://stackoverflow.com/questions/1258275/vertical-rotated-label -in-android me ayudó mucho en mi cse – sakshi

12

En androide para cualquier nuevo punto de vista hay un método llamado setRotation(float) se puede usar

textview.setRotation(float); 

pero por favor tenga en cuenta que este método se agrega en el nivel de API 11

así que si quieres apoyarla Puede utilizar esta

if (Build.VERSION.SDK_INT < 11) { 

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

    watermarkText.setRotation(progress); 
} 
+1

Un poco más de explicación sería bueno. –

+0

He editado la respuesta para obtener más información –

39

Prueba este ::

<TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_gravity="center" 
       android:rotation="-95" 
       android:text="2" 
       /> 
+1

FYI. Su necesidad Build.VERSION.SDK_INT> 11 – MilapTank

+2

problema en este enfoque es el tamaño de ancho no cambia. ¿Alguna idea de cómo superar esto? – abh22ishek

3

[SOLUCIONADO] Después de un año de este ser en mi lista de cubo sin ningún tipo adecuado respuestas en los foros ¡Finalmente he ordenado esto!

El truco aquí es codificar el layout_width y el layout_height del TextView más grande de lo que jamás será el texto, p. Ej. 100dp x 100dp.

luego colocar el TextView en un FrameLayout y girar fuera de recorte para la FrameLayoutandroid:clipChildren="false" y clip para el relleno fuera de la TextView android:clipToPadding="false":

TextView with hard-coded height and width

El TextView ahora flotará en el FrameLayout. Use la configuración de gravedad TextView para mover el texto dentro de su límite.

A continuación, utilice la configuración layout_gravity para mover el límite dentro de la matriz FrameLayout dentro de ella:

Aquí es un ejemplo de la derecha y texto alineado inferior girada 90 grados:

Solution example

[ACTUALIZAR] XML de ejemplo para una carcasa de vista de marco rotado texto:

 <FrameLayout 
      android:layout_width="@dimen/item_col_width_val" 
      android:layout_height="match_parent" 
      android:layout_weight="0.25" 
      android:padding="@dimen/table_header_margin"> 
      <TextView 
       android:layout_width="@dimen/table_title_row_height" 
       android:layout_height="@dimen/table_title_row_height" 
       android:layout_gravity="bottom|end" 
       android:gravity="bottom" 
       android:rotation="-90" 
       android:text="@string/asm_col_title_in_stock" 
       android:textColor="@color/colorGood" /> 
     </FrameLayout> 
+0

Comparta su código xml para que podamos entender más rápidamente su explicación de su respuesta. – ProgDevCode

+0

@ProgDevCode agregó algunos XML según lo solicitado. – user7653815

4
<TextView 
      android:id="@+id/rotated_text" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentLeft="true" 
      android:layout_centerVertical="true" 
      android:alpha=".3" 
      android:background="@drawable/grey_capsule" 
      android:gravity="center" 
      android:textColor="@android:color/white" 
      android:textSize="14sp" 
      android:padding="4dp" 
      android:layout_marginLeft="-50dp" 
      android:rotation="-90" 
      android:text="Andrew Coder" /> 
+0

Gracias ........... –

0

Si no necesita animación, puede probar una solución provista en un question similar. Se escribirá un texto de abajo hacia arriba.

Es compatible con todas las características del TextView básicos:

  • tamaño del texto
  • color del texto
  • fuente del texto
  • relleno de texto
  • uso a través de XML

punto principal es anular onDraw() y onMeasure() métodos basados ​​en parámetros de su texto:

@Override 
    protected void onDraw(Canvas canvas) 
    { 
     super.onDraw(canvas); 

     if (!this._text.isEmpty()) 
     { 
      float textHorizontallyCenteredOriginX = this._measuredHeight/2f; 
      float textHorizontallyCenteredOriginY = this._ascent; 

      canvas.translate(textHorizontallyCenteredOriginY, textHorizontallyCenteredOriginX); 
      canvas.rotate(-90); 
      canvas.drawText(this._text, 0, 0, this._textPaint); 
     } 
    } 

    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) 
    { 
     try 
     { 
      this._textPaint.getTextBounds(this._text, 0, this._text.length(), this._textBounds); 

      this._tempView = new TextView(getContext()); 
      this._tempView.setPadding(this._leftPadding, this._topPadding, this._rightPadding, this._bottomPadding); 
      this._tempView.setText(this._text); 
      this._tempView.setTextSize(TypedValue.COMPLEX_UNIT_PX, this._textSize); 
      this._tempView.setTypeface(this._typeface); 

      this._tempView.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 

      this._measuredWidth = this._tempView.getMeasuredHeight(); 
      this._measuredHeight = this._tempView.getMeasuredWidth(); 

      this._ascent = this._textBounds.height()/2 + this._measuredWidth/2; 

      setMeasuredDimension(this._measuredWidth, this._measuredHeight); 
     } 
     catch (Exception e) 
     { 
      setMeasuredDimension(widthMeasureSpec, heightMeasureSpec); 
      Log.e(LOG_TAG, Log.getStackTraceString(e)); 
     } 
    } 

Por favor, miren Vertical (rotated) label in Android para ver el código fuente completo.

Cuestiones relacionadas