Android set the gravity for a TextView programmati

2019-01-16 03:08发布

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?

6条回答
时光不老,我们不散
2楼-- · 2019-01-16 03:26

Use this code

        TextView textView = new TextView(YourActivity.this);
        textView.setGravity(Gravity.CENTER | Gravity.TOP);
        textView.setText("some text");
查看更多
叼着烟拽天下
3楼-- · 2019-01-16 03:38

This will center the text in a text view:

TextView ta = (TextView) findViewById(R.layout.text_view);
LayoutParams lp = new LayoutParams();
lp.gravity = Gravity.CENTER_HORIZONTAL;
ta.setLayoutParams(lp);
查看更多
劫难
4楼-- · 2019-01-16 03:38

You should use textView.setGravity(Gravity.CENTER_HORIZONTAL);.

Remember that using

LinearLayout.LayoutParams layoutParams =new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
layoutParams2.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;

won't work. This will set the gravity for the widget and not for it's text.

查看更多
Bombasti
5楼-- · 2019-01-16 03:40

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"
 ...
 .../>
查看更多
【Aperson】
6楼-- · 2019-01-16 03:42
textView.setGravity(Gravity.CENTER | Gravity.BOTTOM);

This will set gravity of your textview.

查看更多
劫难
7楼-- · 2019-01-16 03:43
labelTV.setGravity(Gravity.CENTER | Gravity.BOTTOM);

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

查看更多
登录 后发表回答