如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?
当前回答
对于那些想知道如何在其TextView元素中垂直居中,同时将其保持在左侧(水平)的人:
android:gravity="center"
android:textAlignment="viewStart"
其他回答
如果使用的是相对布局:
<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"/>
在任何视图的ConstraintLayout中:
(使用约束布局时,将高度和宽度设置为0,并让约束管理视图边界。)
<View
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
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);
在我看来,
android:gravity="center"
优于,
android:layout_centerInParent="true"
这比,
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
至少用于格式化文本。
我不认为,你真的需要这样做,只需像这样在布局文件中定义你的TextView
<RelativeLayout
android:layout_width="width"
android:layout_height="height">
<TextView
android:id="@+id/yourid"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your text" />
</RelativeLayout>
推荐文章
- 如何在TextView中添加一个子弹符号?
- PreferenceManager getDefaultSharedPreferences在Android Q中已弃用
- 在Android Studio中创建aar文件
- 修改抽射超时时间
- 如何通过数据从第二个活动到第一个活动时按回?——安卓
- 如何在android中获得当前前景活动上下文?
- 如何在Android中获取当前日期?
- 获取Android设备名称
- 在WebView中上传文件
- 加载HTML文件到WebView
- Android:为什么视图没有maxHeight ?
- 如何获得具有已知资源名称的资源id ?
- 在Android上将字符串转换为整数
- 为什么“System.out。”println“工作在Android?
- WebView显示err_cleartext_not_allowed尽管站点是HTTPS