如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?
当前回答
您可以将重力设置为垂直居中,将文本对齐设置为居中。
<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:gravity="center"
优于,
android:layout_centerInParent="true"
这比,
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
至少用于格式化文本。
TextView的高度和宽度是换行内容,然后文本视图中的文本始终居中,然后使用以下命令在父布局中居中:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Hello.."/>
</RelativeLayout>
对于LinearLayout,代码也相同:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello.."/>
</LinearLayout>
从语法上讲,父级是RelativeLayout java代码,这在运行时使用类似的代码
TextView textView1 =(TextView)findViewById(R.id.texView1);
RelativeLayout.LayoutParams layoutParams = RelativeLayout.LayoutParams)textView1.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
textView1.setLayoutParams(layoutParams);
如果您试图在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>
应用重力:
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"
/>
推荐文章
- Android是否保留。apk文件?如果有,在哪里?
- 在Android 5棒棒糖中,通知栏图标变成白色
- 从URI获取真实路径,Android奇巧新的存储访问框架
- 如何检查JSON键是否存在?
- ImageView -有高度匹配宽度?
- 如何确定在android文件的MIME类型?
- 这是在Android中获取用户位置的好方法
- Android从左到右幻灯片动画
- 如何检索视图的维度?
- 如何改变菜单项的文本颜色在安卓?
- Android选择器和文本颜色
- 视图绑定-我如何获得包含布局的绑定?
- 在Android Studio中改变矢量资产的填充颜色
- 在构建中编写注释的语法是什么?gradle文件?
- 如何以编程方式添加按钮色调