如何在 Android 中从 Java 端将 android:gravity 设置为 TextView
我可以在文本视图的 xml 中使用 android:gravity="bottom|center_horizontal"
来获得我想要的结果,但我需要以编程方式执行此操作。如果在 relativelayout
中很重要,我的文本视图位于 tablerow
内。
我已经尝试过:
LayoutParams layoutParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
labelTV.setLayoutParams(layoutParams);
但是如果我理解正确的话,那会将其应用于tablerow
,而不是textview?
I can use android:gravity="bottom|center_horizontal"
in xml on a textview to get my desired results, but I need to do this programmatically. My textview is inside a tablerow
if that matters in a relativelayout
.
I have tried:
LayoutParams layoutParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
labelTV.setLayoutParams(layoutParams);
But if I understand correctly, that would apply it to the tablerow
, not the textview?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
Kotlin 版本(感谢 Thommy)
另外,您是在谈论重力还是layout_gravity?后者在RelativeLayout中不起作用。
Kotlin version (thanks to Thommy)
Also, are you talking about gravity or about layout_gravity? The latter won't work in a RelativeLayout.
这将使文本在文本视图中居中:
This will center the text in a text view:
我们可以在任何视图上设置布局重力,如下所示 -
这相当于下面的 xml 代码
We can set layout gravity on any view like below way-
This is equilent to below xml code
您应该使用textView.setGravity(Gravity.CENTER_HORIZONTAL);。
请记住,使用
不会起作用。这将为小部件而不是其文本设置重力。
You should use
textView.setGravity(Gravity.CENTER_HORIZONTAL);
.Remember that using
won't work. This will set the gravity for the widget and not for it's text.
使用此代码
Use this code
这将设置文本视图的重力。
This will set gravity of your textview.
通过做一些事情解决了这个问题,首先获取我的
TextView
的height
并除以文本size
以获得总行数可以使用TextView
。获得此值后,您需要将
TextView
maxLines
设置为这个新值。一旦超过最大行数,将
Gravity
设置为Bottom
,它将自动向下滚动。为了使其正常工作,您必须对
TextView
使用append()
,如果您setText()
这将不起作用。此方法的好处是,无论
TextView
的height
和文本size
是多少,都可以动态使用它。如果您决定修改布局,此代码仍然有效。Solved this by doing a few things, first getting the
height
of myTextView
and diving it by the textsize
to get the total amount of lines possible with theTextView
.After you get this value you need to set your
TextView
maxLines
to this new value.Set the
Gravity
toBottom
once the maximum amount of lines has been exceeded and it will scroll down automatically.In order for this to work correctly, you must use
append()
to theTextView
, If yousetText()
this will not work.The benefit of this method is that this can be used dynamically regardless of the
height
of yourTextView
and the textsize
. If you decide to make modifications to your layout this code would still work.