如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?
当前回答
在任何视图的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,则可以将父视图重心作为中心。这将使您的子元素位于屏幕的中心,然后您可以将您的子视图作为高度和宽度的环绕。
在XML文件中使用。
布局文件
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="@string/stringtext"/>
or:
在Java类中使用
TextView textView =(TextView)findViewById(R.id.texviewid);
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
在对TextView使用gravity时,API级别17中实现了另一种方法-
textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
不知道有什么区别,但它也起作用。但仅适用于API 17级或更高级别。
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Tours"
android:id="@+id/textView" />
你试过这样吗?
<TextView
android:id="+@id/txtVw"
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文件