Fabrizio Mele
Fabrizio Mele

Reputation: 269

Centering textview in linearlayout at runtime

I'm trying to inflate at runtime some textviews into a linearlayout. This the xml layout (the textviews are just dummies):

<LinearLayout
    android:id="@+id/show_textContainer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center"
    android:orientation="vertical"

    >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="10:20"
        android:textAppearance="@style/hugeText"
        />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="10:15"
        android:textAppearance="@style/mediumText"
        />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="10:10"
        android:textAppearance="@style/mediumText"
        />


</LinearLayout>

and this is the rendering from Android Studio:

Rendering

At runtime I create custom TextViews (named DynamicTextView) with my custom style:

public class DynamicTextView extends TextView {
   public DynamicTextView(Context context) {
      super(context, null, R.style.largeText);
   }
}

(R.style.largeText is

<style name="largeText">
    <item name="android:layout_width">fill_parent</item>
    <item name="android:gravity">center</item>
    <item name="android:layout_height">wrap_content</item>
</style>

)

The custom text view added at runtime have also some custom textAppearance (the same of the dummies):

<style name="mediumText">
    <item name="android:textSize">@dimen/mediumTextDimen</item>
    <item name="android:textColor">@color/alarmBlueMedium</item>
    <item name="android:textStyle">bold</item>

</style>

You would expect both dummies and runtime textviews to be aligned in the same way, but, surprise surprise, they don't:

Runtime

What's going on under the hood that I cannot understand?

Upvotes: 1

Views: 619

Answers (1)

Fahriyal Afif
Fahriyal Afif

Reputation: 558

change your textview's layout_width from fill_parent to wrap_content

code snippet

android:layout_width="wrap_content"

Upvotes: 2

Related Questions