Android set the gravity for a TextView programmatically

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?


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

Also, are you talking about gravity or about layout_gravity? The latter won't work in a RelativeLayout.


这会将文本置于文本视图中:

TextView ta = (TextView) findViewById(R.layout.text_view);
LayoutParams lp = new LayoutParams();
lp.gravity = Gravity.CENTER_HORIZONTAL;
ta.setLayoutParams(lp);

We can set layout gravity on any view like below way-

myView = findViewById(R.id.myView);
myView.setGravity(Gravity.CENTER_VERTICAL|Gravity.RIGHT);
 or
myView.setGravity(Gravity.BOTTOM);

This is equilent to below xml code

<...
 android:gravity="center_vertical|right"
 ...
 .../>
链接地址: http://www.djcxy.com/p/65398.html

上一篇: 2D球之间的吸引力

下一篇: Android以编程方式为TextView设置重力