如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?
当前回答
应用重力:
TextView txtView = (TextView) findViewById(R.id.txtView);
txtView.setGravity(Gravity.CENTER_HORIZONTAL);
对于垂直:
txtView.setGravity(Gravity.CENTER_VERTICAL);
在XML中:
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="@string/Hello_World"
/>
其他回答
如果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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/stringname"
android:layout_centerInParent="true"/>
如果使用LinearLayout
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/stringname"
android:layout_gravity="center"/>
您可以这样做以使文本居中
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" />
您可以将重力设置为垂直居中,将文本对齐设置为居中。
<TextView
android:text="@string/yourText"
android layout_height="wrap_content"
android layout_height="wrap_content"
android:gravity="center_vertical"
android:textAlignment="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);
推荐文章
- 警告: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文件