如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?
当前回答
使用android: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" />
我假设您使用的是XML布局。
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="@string/**yourtextstring**"
/>
还可以根据需要使用重力center_vertical或center_horizontal。
正如@steelthcopter在java:.setGravity(Gravity.CENTER);中评论的那样;。
对于Kotlin用户,.egravity=重力.CENTER
使用下面的xml代码,它对我有用,你可以改变它在中心的方向
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:background="@color/colorPrimaryDark"
android:gravity="center"
android:layout_height="wrap_content">
<TextView
android:id="@+id/id_text"
android:layout_width="wrap_content"
android:textSize="18sp"
android:textColor="@android:color/white"
android:textStyle="normal"
android:layout_height="wrap_content"
android:text="centre me"/>
</LinearLayout>
android:layout_centerInParent="true"
这在与RelativeLayout一起使用时有效,其中布局的高度和宽度设置为wrap_content。
如果您正在使用RelativeLayout,请尝试在TextView标记中使用此属性:
android:layout_centerInParent= true
推荐文章
- 警告: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文件