TextView setGravity() doesn't work in java
Asked Answered
Q

3

12

I'm stuck on a problem and I don't know, what causes it. I have a very simple Layout like this:

<?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 inside another layout. If I change the gravity inside the xml I see same Result in Layout-Editor and on my phone. If I wanna apply the Gravity programatically like with myTextView.setGravity(Gravity.CENTER) it doesn't Change anything. And I cannot set LayoutGravity in Java on a TextView

I'll tried for debug purposes to include them three times each with another gravity which does work even. So I assume everything is alright with my Layout and there has to be a Bug or something else I miss. Can someone give me a hint what I also can try, or what causes this problem?

Quirinus answered 14/4, 2012 at 15:55 Comment(0)
P
30

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

Plow answered 14/4, 2012 at 16:1 Comment(4)
how can I get The intrinsicWidth of the TextView after giving it "fill_parent", because getWidth gives me the width of parent LienearLayoutQuirinus
why do you need that for setting gravity only?Plow
because its not setting gravity only, but rezising the text, which works if I get the correct width of itQuirinus
"rezising the text" do you mean it changes the text size too? it shouldn't be possiblePlow
D
7

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);
Dunnock answered 19/7, 2012 at 7:34 Comment(0)
D
2

When you use LinearLayout as parent, then layout_gravity comes in picture which align control but not content inside the control so, Instead using android:layout_gravity use android:gravity.

Desperado answered 14/4, 2012 at 15:59 Comment(1)
Ah sorry it was my fault... I want to set LayoutGravity because Gravity does nothing... updated my QuestionQuirinus

© 2022 - 2024 — McMap. All rights reserved.