Android configured gravity for TextView programmatically

I can use android:gravity="bottom|center_horizontal" in xml in text form to get the desired results, but I need to do this programmatically. My text view is inside a tablerow , if that matters in relativelayout .

I tried:

 LayoutParams layoutParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL); labelTV.setLayoutParams(layoutParams); 

But if I understood correctly, would that apply it to tablerow , not text?

+203
source share
7 answers
 labelTV.setGravity(Gravity.CENTER | Gravity.BOTTOM); 

Kotlin version (thanks Tommy)

 labelTV.gravity = Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM 

Also, are you talking about gravity or layout_gravity? The latter will not work in RelativeLayout.

+493
source

This centers the text in text form:

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

We can set the density of placement on any form, as shown below:

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

This is tantamount to below xml code

 <... android:gravity="center_vertical|right" ... .../> 
+6
source

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

Remember that with

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

will not work. This will set the gravity for the widget, not for the text.

+2
source
 textView.setGravity(Gravity.CENTER | Gravity.BOTTOM); 

This will add seriousness to your texture.

+2
source

Use this code

  TextView textView = new TextView(YourActivity.this); textView.setGravity(Gravity.CENTER | Gravity.TOP); textView.setText("some text"); 
+1
source

Solve this by doing a few things, first getting the height my TextView and loading it onto the text size to get the total number of possible lines with the TextView .

 int maxLines = (int) TextView.getHeight() / (int) TextView.getTextSize(); 

After you get this value, you need to set the TextView maxLines to this new value.

 TextView.setMaxLines(maxLines); 

Set Gravity to Bottom as soon as the maximum number of lines is exceeded and it automatically scrolls down.

 if (TextView.getLineCount() >= maxLines) { TextView.setGravity(Gravity.BOTTOM); } 

In order for this to work correctly, you must use append() for the TextView , if you setText() , this will not work.

 TextView.append("Your Text"); 

The advantage of this method is that it can be used dynamically regardless of the height your TextView and text size . If you decide to make changes to your layout, this code will still work.

0
source

Source: https://habr.com/ru/post/1412512/


All Articles