2011-01-25 44 views
60

Tôi muốn để cho nó trông như thế này:Làm cách nào để căn giữa văn bản hai dòng trong một TextView trên Android?

| two | 
| lines | 

Dưới đây là cách bố trí hiện nay, không làm việc ở tất cả.

<RelativeLayout 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:gravity="center_vertical"> 
    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="two\nlines" 
     android:layout_gravity="center_vertical" 
     android:layout_centerInParent="true"/> 
</RelativeLayout> 

Bất kỳ ý tưởng nào? Cảm ơn!

Trả lời

184

Nếu bạn chỉ muốn tập trung nó (tôi giả sử \n đang làm việc để phân chia các dòng) , chỉ cần thêm android:gravity="center_horizontal" thay vì layout_gravity.
Sử dụng trọng lượng bố cục di chuyển TextView thực tế, sử dụng trọng lực ảnh hưởng đến nội dung của TextView.

1

Tôi nghĩ rằng bạn phải làm điều đó từ Java:

<RelativeLayout 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:gravity="center_vertical"> 
    <TextView 
     android:id="@+id/the_text_view" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_vertical" 
     android:layout_centerInParent="true"/> 
</RelativeLayout> 

Sau đó:

TextView tv = (TextView) findViewById(R.id.the_text_view); 
tv.setText(Html.fromHtml("two<br/>lines")); 
2

Bạn có thể sử dụng:

TextView tv = (TextView) findViewById(R.id.the_text_view); 
tv.setText(Html.fromHtml("two"+"\n"+"lines")); 
-3

Thêm bất động sản

android:lines="2" 

nơi 2 là không có đường bạn có thể thiết lập này không như requirment của bạn

+0

điều này không đặt TextView làm trung tâm, nó chỉ buộc nó có hai dòng. Tuy nhiên, câu trả lời này không phải là quá xấu nó cần phải được downvoted. – Shishdem

+0

không giải quyết bất cứ điều gì -.- –

+0

Nó sẽ không thực hiện bất kỳ tác động nào theo yêu cầu. Căn chỉnh sẽ không được căn giữa. – deva11

8

Đã phải thêm cả gravitylayout_gravity để căn chỉnh cả hai TextView và nội dung của nó

android:gravity="center_horizontal" 
android:layout_gravity="center_horizontal" 
2

nếu chiều rộng của bạn là wrap_content, bạn phải thiết lập trọng lực và layout_gravity cả hai như "center_horizontal"

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="two\nlines" 
    android:layout_gravity="center_horizontal" 
    android:gravity="center_horizontal"/> 

Tuy nhiên, nếu chiều rộng của bạn là "match_parent, bạn sẽ chỉ phải thiết lập lực hấp dẫn như 'center_horizontal'

<TextView 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="two\nlines" 
    android:gravity="center_horizontal"/> 

Hy vọng điều đó sẽ hữu ích!

+0

Cảm ơn. Những công việc này. Đặt cả 'lực hấp dẫn' và 'layout_gravity' đều là thủ thuật cho tôi. –

Các vấn đề liên quan