与 android 对齐文本中心
我知道这听起来很容易。我需要将文本放在中心,但是当文本太长时,它需要位于下方,但仍与 xml 的中心对齐。
这是我的代码:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/showdescriptioncontenttitle"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:layout_centerHorizontal="true"
>
<TextView
android:id="@+id/showdescriptiontitle"
android:text="Title"
android:textSize="35dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
我放置了 paddingTop 和 Bottom 因为我需要一些空间。 PS:我的代码比较大;它位于相对布局中。
I know it sounds easy. I need to put a text in center, but when the text is too long it needs to go below, but still align in the center of my xml.
Here's my code :
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/showdescriptioncontenttitle"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:layout_centerHorizontal="true"
>
<TextView
android:id="@+id/showdescriptiontitle"
android:text="Title"
android:textSize="35dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
I put paddingTop and Bottom because I need some space.
PS: My code is bigger; it's in a RelativeLayout.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
将
TextView
中的android:gravity
参数设置为center
。为了测试不同布局参数的效果,我建议为每个元素使用不同的背景颜色,这样您就可以看到布局如何随着重力、layout_gravity 或其他参数的变化而变化。
Set also
android:gravity
parameter inTextView
tocenter
.For testing the effects of different layout parameters I recommend to use different background color for every element, so you can see how your layout changes with parameters like gravity, layout_gravity or others.
用这种方式
use this way
在xml中使用这种方式
use this way in xml
您可以使用以下内容:
布局需要是相对的才能使用“center”属性。
You can use the following:
The layout needs to be relative for the "center" property to be used.
在 TextView 中添加
android:gravity="center"
就可以了(父布局是Relative/Linear
)!另外,您应该避免使用 dp 作为字体大小。使用 sp 代替。
Adding
android:gravity="center"
in your TextView will do the trick (be the parent layout isRelative/Linear
)!Also, you should avoid using dp for font size. Use sp instead.
只需添加这两行即可;
Just add these 2 lines;
在 TextView 上添加布局重力和重力以及中心值
add layout_gravity and gravity with center value on TextView
或者
两者都适合我。
or
both works for me.
或者检查一下,这将有助于一次对齐所有元素。
Or check this out this will help align all the elements at once.
如果您想更改 mainActivity.java 文件中的对齐方式,请使用重力。例如:
chatMsg 是我的textView。我希望文本右对齐,并且这段代码运行良好。
If you want to change the alignment from the mainActivity.java file, then use the gravity. For example:
chatMsg is my textView. I wanted the text to be right aligned and this code worked well.
您可以通过添加这些行轻松完成此操作
you can easily done this by adding these lines