如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?
当前回答
通过.xml文件重力可以设置为中心,如下所示
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="In the center"
/>
通过java,以下是解决特定问题的方法
textView1.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
其他回答
简单地,在XML文件中,将文本视图重心设置为中心:
<TextView
android:gravity="center" />
必须这样设置“重力”:
(textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
<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);
使用android:textAlignment=“center”
<TextView
android:text="HOW WAS\nYOUR\nDAY?"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="center"
android:id="@+id/textView5"
/>
在任何视图的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" />
推荐文章
- 如何在android中获得当前前景活动上下文?
- 如何在Android中获取当前日期?
- 获取Android设备名称
- 在WebView中上传文件
- 加载HTML文件到WebView
- Android:为什么视图没有maxHeight ?
- 如何获得具有已知资源名称的资源id ?
- 在Android上将字符串转换为整数
- 为什么“System.out。”println“工作在Android?
- WebView显示err_cleartext_not_allowed尽管站点是HTTPS
- Android M权限:对shouldShowRequestPermissionRationale()函数的使用感到困惑
- 为什么构建类型与产品风味不同?
- 我如何在一个片段中访问getSupportFragmentManager() ?
- 调试在哪里。Android Studio中的密钥存储库
- 从资产中读取文件