如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?


当前回答

重新排列布局、图像或文本视图的位置属于对齐主题。因此,如果您想将图像src垂直放置在中间,应该使用下面编写的代码

android:layout_centerVertical="true"

和中心水平

android:layout_centerHorizontal="true"

否则,我认为我们也可以使用重力将每个元素放在父布局的中间,如android:gravity=“center”

其他回答

对于kotlin:

如果要将TextView从代码中居中:

textView.gravity = Gravity.CENTER

如果要水平居中:

textView.gravity = Gravity.CENTER_HORIZONTAL

或者,垂直居中:

textView.gravity = Gravity.CENTER_VERTICAL

TextView的高度和宽度是换行内容,然后文本视图中的文本始终居中,然后使用以下命令在父布局中居中:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Hello.."/>
</RelativeLayout>

对于LinearLayout,代码也相同:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello.."/>
</LinearLayout>

从语法上讲,父级是RelativeLayout java代码,这在运行时使用类似的代码

TextView textView1 =(TextView)findViewById(R.id.texView1);
RelativeLayout.LayoutParams layoutParams = RelativeLayout.LayoutParams)textView1.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
textView1.setLayoutParams(layoutParams);

简单地,在XML文件中,将文本视图重心设置为中心:

<TextView
    android:gravity="center" />
android:gravity="center" 

这就行了

这是我在应用程序中使用的答案。它在屏幕中央显示文本。

<TextView
    android:id="@+id/txtSubject"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/subject"
    android:layout_margin="10dp"
    android:gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge" />