【问题标题】:TextView text is not centredTextView 文本不居中
【发布时间】:2014-02-14 23:10:34
【问题描述】:

我试图在我的文本视图中居中一些代码,但它似乎一直保持左对齐:

<LinearLayout 
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerVertical="true"
    android:layout_above="@+id/myButtons">    

<!-- Text -->
<TextView
android:id="@+id/myText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="22sp"
android:text="Test"
    android:textStyle="bold" />

<!-- And the thumbnail -->
<ImageView
android:id="@+id/image" 
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp"  
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:contentDescription="@string/image_text"
    android:layout_gravity="center" />      
</LinearLayout>  

图像(如果有,有时会设置为 Visibility.GONE)居中对齐。只是我无法让文本居中对齐。

欢迎任何想法。谢谢!

【问题讨论】:

  • 你试过我的答案了吗?
  • 是的,我在你的回答下回复了:)
  • 我已经编辑了我的答案看看
  • LayoutParams.FILL_PARENT 根据 Eclipse 已被弃用。仍然可以安全使用吗?
  • 更改为 LayoutParams.MATCH_PARENT

标签: alignment android-linearlayout textview android


【解决方案1】:

在你的 textview 属性中添加 android:gravity="center_horizontal|center_vertical" 以使居中

<TextView
    android:id="@+id/myText"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal|center_vertical"
    android:textSize="22sp"
    android:text="Test"
    android:textStyle="bold" />

在 imageview 消失后使 Textview fillParent

以编程方式设置 textview fill_parent 的高度

textview.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT,0));
                                          ^                            ^
                                          height                      width                    

【讨论】:

  • 感谢 user2675669,这使它水平居中对齐,这比我得到的要远,所以谢谢!但是只有一件事,在图像视图被隐藏的情况下(Visibility.GONE),我如何让文本视图占用所有可用空间?因为现在,它不是垂直居中对齐,而是顶部对齐(大概是因为它设置为在图像填充父时包装内容?)。任何想法表示赞赏,谢谢!
猜你喜欢
  • 2012-04-18
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多