如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?
当前回答
在对TextView使用gravity时,API级别17中实现了另一种方法-
textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
不知道有什么区别,但它也起作用。但仅适用于API 17级或更高级别。
其他回答
如果您试图在TableLayout中的TableRow上居中文本,以下是我实现这一点的方法:
<TableRow android:id="@+id/rowName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dip" >
<TextView android:id="@+id/lblSomeLabel"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:layout_width="0dp"
android:layout_weight="100"
android:text="Your Text Here" />
</TableRow>
如果使用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>
我添加了xml片段,以使文本视图中心在线性和相对布局中对齐。
在线性布局中
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text In Center"
android:layout_gravity="center"
android:gravity="center"/>
在相对布局中
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Text In Center"
android:layout_centerInParent= true/>
字体填充也会影响文本的位置,您可以通过添加includefontpadding=false来删除它
<TextView
android:includeFontPadding="false"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" />
使用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"
/>
推荐文章
- BottomSheetDialogFragment的圆角
- 在应用程序启动时出现“无法获得BatchedBridge,请确保您的bundle被正确打包”的错误
- 我如何改变默认对话框按钮的文本颜色在安卓5
- 更改单选按钮的圆圈颜色
- 如何在android中复制一个文件?
- adb找不到我的设备/手机(MacOS X)
- 如何在新的材质主题中改变背面箭头的颜色?
- androidviewpager与底部点
- 相同的导航抽屉在不同的活动
- 如何从视图中获得托管活动?
- 单一的TextView与多种颜色的文本
- 如何在非活动类(LocationManager)中使用getSystemService ?
- 在清单中注册应用程序类?
- Android:从数组中编程创建旋转器
- Android命令行工具sdkmanager总是显示:警告:无法创建设置