如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?
当前回答
There are 2 ways to do this :
1. From Xml
use :
<TextView
.........
android:gravity="center"/>
2. From Java class
use :
[textview].setGravity(Gravity.CENTER);
其他回答
使用android:gravity=“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);
非常感谢。
如果您正在使用RelativeLayout,请尝试在TextView标记中使用此属性:
android:layout_centerInParent= true
对于线性布局:在XML中,使用以下内容
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical|center_horizontal"
android:text="Your Text goes here"
/>
要在运行时执行此操作,请在活动中使用类似的内容
TextView textView1 =(TextView)findViewById(R.id.texView1);
textView1.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
对于相对布局:在XML中使用类似于
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:text="Your Text goes here"
/>
要在运行时执行此操作,请在活动中使用类似的内容
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"
至少用于格式化文本。
推荐文章
- 警告: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文件