如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?
当前回答
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HELLO"
android:textColor="@color/colorPrimaryDark"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</android.support.constraint.ConstraintLayout>
其他回答
字体填充也会影响文本的位置,您可以通过添加includefontpadding=false来删除它
<TextView
android:includeFontPadding="false"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" />
<TextView
android:id="+@id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
/>
正如许多答案所表明的那样,上述工作正常。
android:gravity="center"
如果要使其垂直居中:
android:gravity="center_vertical"
或仅水平:
android:gravity="center_horizontal"
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:layout_centerInParent="true"
以及其他布局
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文件