2013-10-15 3 views
0

Je souhaite dessiner du texte sur un rectangle à l'aide de xml. Je veux que le texte soit centré sur le rectangle. Le rectangle et le texte sont à la fois dans une grille pour une raison.textview centré sur le rectangle

<GridLayout 
     android:id="@+id/daily" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center" 
     android:columnCount="3" 
     android:orientation="horizontal" 
     android:rowCount="1" > 

     <TextView android:background="@drawable/green_rect_small" /> 

     <Space android:layout_width="3dp" /> 

     <RelativeLayout> 

      <View 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:background="@drawable/green_rect_large" /> 

      <TextView 
       android:id="@+id/daily_readings" 
       android:background="@drawable/green_rect_large" 
       android:text="@string/daily_readings" 
       android:textColor="@color/white" 
       android:textSize="40sp" /> 
     </RelativeLayout> 
</GridLayout> 

Je ne peux pas l'obtenir fait si je mets le rectangle comme bg de l'affichage du texte ou une vue séparée. Où ai-je tort?

Répondre

1

Définir le rectangle comme l'arrière-plan RelativeLayout puis rendre le centre texte sur elle

<?xml version="1.0" encoding="utf-8"?> 
<GridLayout 
     android:id="@+id/daily" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center" 
     android:columnCount="3" 
     android:orientation="horizontal" 
     android:rowCount="1" xmlns:android="http://schemas.android.com/apk/res/android"> 

     <RelativeLayout 
      android:layout_width="300dp" 
      android:layout_height="200dp" 
      android:background="@drawable/green_rect_large"> 


      <TextView 
       android:id="@+id/daily_readings" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 

       android:text="daily_readings" 
       android:textColor="#FFFFFF" 
       android:textSize="40sp" 
       android:layout_centerInParent="true" /> 

     </RelativeLayout> 
</GridLayout> 
+0

Merci pour votre ramaral de réponse. –

3

Vous n'avez pas besoin d'utiliser un RelativeLayout, ou une vue séparée pour dessiner votre rectangle vert. Si je vous comprends bien, vous pouvez obtenir tout ce que vous êtes désireux avec un seul TextView:

<TextView 
    android:textColor="#FFFFFF" 
    android:background="#339933" 
    android:layout_width="200dp" 
    android:layout_height="50dp" 
    android:gravity="center" 
    android:text="@string/hello_world" /> 

et le résultat est:

enter image description here

+0

Je pourrais ajouter une icône plus tard si le client en veut un alors je garde la disposition relative mais votre chemin est plus efficace. –

Questions connexes