如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?
当前回答
要在中心显示文本,请执行以下操作:
------------------>text<-------------------
使用以下样式:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_contect"
android:gravity="center"
android:text="@string/text"
/>
android:gravity="center"
其他回答
如果TextView的高度和宽度是换行内容,则TextView中的文本始终居中。但如果TextView的宽度为match_parent,高度为match-parent或wrap_content,则必须编写以下代码:
对于RelativeLayout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Hello World" />
</RelativeLayout>
对于LinearLayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Hello World" />
</LinearLayout>
<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>
我假设您使用的是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
我不认为,你真的需要这样做,只需像这样在布局文件中定义你的TextView
<RelativeLayout
android:layout_width="width"
android:layout_height="height">
<TextView
android:id="@+id/yourid"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your text" />
</RelativeLayout>
使用android:gravity=“center”解决问题。
推荐文章
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- 如何设置整个应用程序在纵向模式?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 如何从通知点击发送参数到一个活动?
- 导航目标xxx对于这个NavController是未知的
- 使用ConstraintLayout均匀间距的视图
- 文件google-services错误。模块根文件夹中缺少Json。谷歌服务插件没有它就不能正常工作。