如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?
当前回答
你试过这样吗?
<TextView
android:id="+@id/txtVw"
android:gravity="center"
/>
其他回答
迟到的GUI荣誉奖
我想为这个已经非常棒的线程增加一些价值。最后,在11年后,我们现在有了一种方法,可以从工具箱中拖放TextView,并通过GUI的财产框选择重力。幸运的是,GUI将财产简洁地组合为“center_vertical | center_horizontal”。
<TextView
android:text="This is my sample text."
android:layout_width="match_parent"
android:layout_height="35.7dp"
android:id="@+id/textView2"
android:layout_marginBottom="24.7dp"
android:typeface="sans"
android:textSize="20"
android:gravity="center_vertical|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" />
您也可以使用以下组合:
android:gravity="left|center"
然后,如果文本视图宽度大于“fill_paint”,则文本仍将向左对齐(不居中,因为重力仅设置为“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>
这是我在应用程序中使用的答案。它在屏幕中央显示文本。
<TextView
android:id="@+id/txtSubject"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/subject"
android:layout_margin="10dp"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge" />
推荐文章
- 警告: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文件