如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?
当前回答
在RelativeLayout中,它会很好。
还有另一个按钮和任何你可以添加的东西。
以下内容对我很有用。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff314859"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<TextView
android:id="@+id/txt_logo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="your text here"
android:textSize="30dp"
android:gravity="center"/>
...other button or anything else...
</RelativeLayout>
其他回答
如果TextView没有将height/width属性设置为wrap_content,请使用android:gravity=“center”。但有些人抱怨说,使用这种方法行不通。这是因为它们的布局没有相同的重力。您可以设置
android:layout_gravity=“center”在文本视图中(这仅适用于文本视图)
or
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>
简单地,在XML文件中,将文本视图重心设置为中心:
<TextView
android:gravity="center" />
如果您试图在TableLayout中的TableRow上居中文本,以下是我实现这一点的方法:
<TableRow android:id="@+id/rowName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dip" >
<TextView android:id="@+id/lblSomeLabel"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:layout_width="0dp"
android:layout_weight="100"
android:text="Your Text Here" />
</TableRow>
重新排列布局、图像或文本视图的位置属于对齐主题。因此,如果您想将图像src垂直放置在中间,应该使用下面编写的代码
android:layout_centerVertical="true"
和中心水平
android:layout_centerHorizontal="true"
否则,我认为我们也可以使用重力将每个元素放在父布局的中间,如android:gravity=“center”
推荐文章
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- 如何设置整个应用程序在纵向模式?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 如何从通知点击发送参数到一个活动?
- 导航目标xxx对于这个NavController是未知的
- 使用ConstraintLayout均匀间距的视图
- 文件google-services错误。模块根文件夹中缺少Json。谷歌服务插件没有它就不能正常工作。