如何在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);
其他回答
android:gravity=“center_horizontal”表示文本水平居中。android:gravity=“center_vertical”用于垂直对齐文本中心。android:gravity=“center”用于垂直和水平对齐文本中心。
<TextView
android:layout_width="match_parent"
android:gravity="center_horizontal|center_vertical"
android:layout_height="match_parent" />
文本视图宽度和高度应为match_parent,并在文本视图属性中添加android:gravity=“center”。
在任何视图的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="match_parent"
android:layout_height="match_parent"
android:gravity="center" />
如果要将文本视图的宽度和高度设置为环绕内容,则必须根据父级支持的属性通过布局重力来管理其位置。否则你可以做。
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"/>
推荐文章
- 警告:API ' variable . getjavacompile()'已过时,已被' variable . getjavacompileprovider()'取代
- 安装APK时出现错误
- 碎片中的onCreateOptionsMenu
- TextView粗体通过XML文件?
- 如何使线性布局的孩子之间的空间?
- DSL元素android.dataBinding。enabled'已过时,已被'android.buildFeatures.dataBinding'取代
- ConstraintLayout:以编程方式更改约束
- PANIC: AVD系统路径损坏。检查ANDROID_SDK_ROOT值
- 如何生成字符串类型的buildConfigField
- Recyclerview不调用onCreateViewHolder
- Android API 21工具栏填充
- Android L中不支持操作栏导航模式
- 如何在TextView中添加一个子弹符号?
- PreferenceManager getDefaultSharedPreferences在Android Q中已弃用
- 在Android Studio中创建aar文件