如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?
当前回答
您也可以使用以下组合:
android:gravity="left|center"
然后,如果文本视图宽度大于“fill_paint”,则文本仍将向左对齐(不居中,因为重力仅设置为“center”)。
其他回答
试试看:
如果使用textview height and width match_parent,则使用LinearLayout如果使用textview-height and width wrap_content,则可以将重力文本设置为居中,将文本对齐设置为水平居中,然后在LinearLayout中添加重力中心属性。
XML代码
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAlignment="center"
android:gravity="center"
android:textColor="#000"
android:textSize="30sp"
android:text="Welcome to Android" />
</LinearLayout>
Java代码
您可以通过编程这样做:-
(textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
非常感谢。
对于那些想知道如何在其TextView元素中垂直居中,同时将其保持在左侧(水平)的人:
android:gravity="center"
android:textAlignment="viewStart"
应用重力:
TextView txtView = (TextView) findViewById(R.id.txtView);
txtView.setGravity(Gravity.CENTER_HORIZONTAL);
对于垂直:
txtView.setGravity(Gravity.CENTER_VERTICAL);
在XML中:
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="@string/Hello_World"
/>
在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.setGravity(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文件