如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?
当前回答
在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使用gravity时,API级别17中实现了另一种方法-
textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
不知道有什么区别,但它也起作用。但仅适用于API 17级或更高级别。
在我看来,
android:gravity="center"
优于,
android:layout_centerInParent="true"
这比,
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
至少用于格式化文本。
<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);
如果使用TableLayout,请确保将TableRows的重心也设置为中心。否则它将无法工作。至少在我将TableRow的重心设置为中心之前,它没有对我起作用。
例如,如下所示:
<TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center">
<TextView android:text="@string/chf" android:id="@+id/tv_chf" android:layout_weight="2" android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center"></TextView>
</TableRow>
你试过这样吗?
<TextView
android:id="+@id/txtVw"
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文件