如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?
当前回答
让我们在屏幕中显示全文视图
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello World!"
android:gravity="center"
/>
让我们说相对布局中的文本视图(未满)
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_centerInParent=true
/>
假设Linear_layout中的Textview(未满)
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_gravity="centre"
/>
其他回答
对于那些想知道如何在其TextView元素中垂直居中,同时将其保持在左侧(水平)的人:
android:gravity="center"
android:textAlignment="viewStart"
我假设您使用的是XML布局。
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="@string/**yourtextstring**"
/>
还可以根据需要使用重力center_vertical或center_horizontal。
正如@steelthcopter在java:.setGravity(Gravity.CENTER);中评论的那样;。
对于Kotlin用户,.egravity=重力.CENTER
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HELLO"
android:textColor="@color/colorPrimaryDark"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</android.support.constraint.ConstraintLayout>
试试这种方法,它会奏效的
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="center"/>
</LinearLayout>
试试看:
如果使用textview height and width match_parent,则使用LinearLayout如果使用textview-height and width wrap_content,则可以将重力文本设置为居中,将文本对齐设置为水平居中,然后在LinearLayout中添加重力中心属性。
XML代码
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAlignment="center"
android:gravity="center"
android:textColor="#000"
android:textSize="30sp"
android:text="Welcome to Android" />
</LinearLayout>
Java代码
您可以通过编程这样做:-
(textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
非常感谢。
推荐文章
- PreferenceManager getDefaultSharedPreferences在Android Q中已弃用
- 在Android Studio中创建aar文件
- 修改抽射超时时间
- 如何通过数据从第二个活动到第一个活动时按回?——安卓
- 如何在android中获得当前前景活动上下文?
- 如何在Android中获取当前日期?
- 获取Android设备名称
- 在WebView中上传文件
- 加载HTML文件到WebView
- Android:为什么视图没有maxHeight ?
- 如何获得具有已知资源名称的资源id ?
- 在Android上将字符串转换为整数
- 为什么“System.out。”println“工作在Android?
- WebView显示err_cleartext_not_allowed尽管站点是HTTPS
- Android M权限:对shouldShowRequestPermissionRationale()函数的使用感到困惑