简体   繁体   English

以编程方式在 TextView 中设置文本对齐方式

[英]Programmatically set text alignment in a TextView

In my app, I have a button that creates a TextView with a certain message.在我的应用程序中,我有一个按钮可以创建带有特定消息的 TextView。 How can I set the text alignment of the text to the right of the TextView?如何将文本的文本对齐方式设置为 TextView 的右侧? I see the attribute in XML, but I don't know how to do it in java.我在 XML 中看到了该属性,但我不知道如何在 Java 中进行操作。

In Kotlin you can use something like the below,在 Kotlin 中,您可以使用如下所示的内容,

 val textView = TextView(context)
 textView.apply {
     layoutParams = TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
                                    TableRow.LayoutParams.WRAP_CONTENT)
     textAlignment = View.TEXT_ALIGNMENT_VIEW_START
 }

尝试使用

textView.setGravity(Gravity.RIGHT)

您可以使用设置 textview 的重力

textLabel.setGravity(Gravity.CENTER | Gravity.BOTTOM);

1.) Make sure the width is not set to wrap_content 1.) 确保宽度未设置为 wrap_content

2.) If the text view is inside another container, set gravity to the container. 2.) 如果文本视图在另一个容器内,则为容器设置重力。 Remember that gravity is to align text and stuff like that while layout_gravity is used to align views within a parent.请记住,重力用于对齐文本和类似内容,而 layout_gravity 用于对齐父级中的视图。

3.) TextAlign aligns text at the beginning, end, left, or right of the container. 3.) TextAlign 在容器的开始、结束、左侧或右侧对齐文本。 Gravity is a bit more flexible with Center_Vertical, Center_Horizontal, or Center. Gravity 使用 Center_Vertical、Center_Horizo​​ntal 或 Center 更灵活一些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM