Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextView setGravity() doesn't work in java

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?

like image 620
Rafael T Avatar asked Apr 14 '12 15:04

Rafael T


People also ask

How do you call the TextView in Java file?

In this code example of MainActivity. java file, first of all, we access the TextView from the xml file by the line "TextView txtView = findViewById(R. id. text_view);" and in the next line we set the text by the line "txtView.

Which method is used to read value of a TextView in Java?

getText(). toString(); int A = Integer. parseInt(a);

How can I center text programmatically in android?

To center align text in TextView in Kotlin Android, set android:textAlignment attribute with the value “center” in layout file, or programmatically set the textAlignment property of the TextView object with View. TEXT_ALIGNMENT_CENTER in activity file.

How do I center a TextView layout?

If in linearlayout your orientation vertical, you can put the textview in the "horizontal center" by android:layout_gravity="center" . For centering textview vertically you need to set layout_height of textview to match_parent and set android:gravity to "center".


1 Answers

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

like image 102
waqaslam Avatar answered Sep 28 '22 11:09

waqaslam