如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?
当前回答
如果TextView没有将height/width属性设置为wrap_content,请使用android:gravity=“center”。但有些人抱怨说,使用这种方法行不通。这是因为它们的布局没有相同的重力。您可以设置
android:layout_gravity=“center”在文本视图中(这仅适用于文本视图)
or
android:gravity=“center”在父布局中(这将适用于其中的所有视图)
其他回答
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="In the center"/>
以上是使用.xml文件进行设置。
但我更喜欢java版本,因为如果需要,您也可以在运行状态下在代码中禁用它。下面是java代码。
textView1.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
在任何视图的ConstraintLayout中:
(使用约束布局时,将高度和宽度设置为0,并让约束管理视图边界。)
<View
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Tours"
android:id="@+id/textView" />
重新排列布局、图像或文本视图的位置属于对齐主题。因此,如果您想将图像src垂直放置在中间,应该使用下面编写的代码
android:layout_centerVertical="true"
和中心水平
android:layout_centerHorizontal="true"
否则,我认为我们也可以使用重力将每个元素放在父布局的中间,如android:gravity=“center”
在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中添加一个子弹符号?
- 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