如何在 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)
您应该使用textView.setGravity(Gravity.CENTER_HORIZONTAL);。
请记住,使用
LinearLayout.LayoutParams layoutParams =new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
layoutParams2.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
不会起作用。这将为小部件而不是其文本设置重力。
通过做一些事情解决了这个问题,首先获取我的 TextView
的 height
并除以文本 size
以获得总行数可以使用TextView
。
int maxLines = (int) TextView.getHeight() / (int) TextView.getTextSize();
获得此值后,您需要将 TextView
maxLines
设置为这个新值。
TextView.setMaxLines(maxLines);
一旦超过最大行数,将Gravity
设置为Bottom
,它将自动向下滚动。
if (TextView.getLineCount() >= maxLines) {
TextView.setGravity(Gravity.BOTTOM);
}
为了使其正常工作,您必须对 TextView
使用 append()
,如果您 setText()
这将不起作用。
TextView.append("Your Text");
此方法的好处是,无论 TextView
的 height
和文本 size
是多少,都可以动态使用它。如果您决定修改布局,此代码仍然有效。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
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.