如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?
当前回答
如果要将文本视图的宽度和高度设置为环绕内容,则必须根据父级支持的属性通过布局重力来管理其位置。否则你可以做。
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"/>
其他回答
试试看:
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
/>
最简单的方法(令人惊讶的是,只有在评论中才会提到,所以我才会发布答案)是:
textview.setGravity(Gravity.CENTER)
在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
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" />
对于线性布局:在XML中,使用以下内容
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical|center_horizontal"
android:text="Your Text goes here"
/>
要在运行时执行此操作,请在活动中使用类似的内容
TextView textView1 =(TextView)findViewById(R.id.texView1);
textView1.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
对于相对布局:在XML中使用类似于
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:text="Your Text goes here"
/>
要在运行时执行此操作,请在活动中使用类似的内容
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);
推荐文章
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- 如何设置整个应用程序在纵向模式?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 如何从通知点击发送参数到一个活动?
- 导航目标xxx对于这个NavController是未知的
- 使用ConstraintLayout均匀间距的视图
- 文件google-services错误。模块根文件夹中缺少Json。谷歌服务插件没有它就不能正常工作。