Android TextView 文本对齐方式 [英] Android TextView text alignment
问题描述
我不知道如何提前对齐文本.但我将分别进行水平和垂直对齐.以编程方式设置对齐的最佳方法是什么.我可以这样做:
I don't know how text is going to be aligned in advance. But I will be getting horizontal and vertical alignment separately. What is the best way to set the alignment programmatically. I can do something like this:
/**
* Sets text alignment
* @param alignment
*/
public void setAlignment(String alignment, String vAlignment){
if (alignment.equals("Left")){
if (vAlignment.equals("Top"))
setGravity(Gravity.LEFT | Gravity.TOP);
else if (vAlignment.equals("Center"))
setGravity(Gravity.LEFT | Gravity.CENTER);
else if (vAlignment.equals("Bottom"))
setGravity(Gravity.LEFT | Gravity.BOTTOM);
}
//same for other horizontal alignments
有没有其他方法可以做到这一点?稍后我还必须查看文本对齐和拉伸,因此如果我可以一个接一个地分别设置水平和垂直对齐方式会更容易.可能吗?
Is there any other way of doing this? I will also have to look at text justification and stretching later on, so it would be easier if I could have horizontal and vertical alignments set separately one after another. Is it possible?
推荐答案
您可以尝试使用运算符 |=
.它的行为与 +=
完全一样,并且适用于 int
值.
You can try using the operator |=
. It behaves exactly like +=
, and it is suitable for int
values.
public void setAlignment(String alignment, String vAlignment){
int myGravity = 0;
if (alignment.equals("Left")){
myGravity |= Gravity.LEFT;
}
if (vAlignment.equals("Top")){
myGravity |= Gravity.TOP;
}
...
myTextView.setGravity(myGravity);
}
这篇关于Android TextView 文本对齐方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!