TextView setGravity () not working in java

I am stuck in a problem and I do not know what causes it. I have a very simple layout:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/my_text_view" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_gravity="NOTE_THIS" android:textColor="#FFFFFF" android:textSize="22dp" android:text="TestText"/> </LinearLayout> 

which is included in another layout. If I change the gravity inside xml, I see the same result in the layout editor and on my phone. If I want to apply Gravity programmatically, as with myTextView.setGravity(Gravity.CENTER) , this will not change anything. And I can not install LayoutGravity in Java on TextView

I will try for debugging purposes to enable them three times each with a different severity that even works. Therefore, I assume that everything is in order with my layout, and there should be a Bug or something else that I missed. Can someone give me a hint that I can also try, or what causes this problem?

+7
source share
3 answers

Set the width of the TextView as android:layout_width="fill_parent" , then you can set it programmatically using myTextView.setGravity(Gravity.CENTER)

+24
source

You need to set the gravity of the LayoutParams object instead of the view itself:

 TextView tv = new TextView(getApplicationContext()); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); lp.gravity = Gravity.CENTER; tv.setLayoutParams(lp); 
+5
source

When you use LinearLayout as the parent, then layout_gravity appears in the image that aligns the control, but not the content inside the control. Instead of using android:layout_gravity use android:gravity .

+1
source

All Articles