1

I currently have this xml:

<TextView android:id="@+id/dummy"
android:layout_width="match_parent"
android:layout_height="match_parent" 
android:gravity="center"
android:text="@string/test"
android:textStyle="bold" />

And im trying to convert it to a java version so that I can set a typeface:

setContentView(R.layout.activity_main);

// the get the activity_main layout (getContentView method does not exist?)
FrameLayout layout = (FrameLayout) findViewById(android.R.id.content);

final TextView textView = new TextView(context);
textView.setId(R.id.dummy);

FrameLayout.LayoutParams contentLayout = new FrameLayout.LayoutParams(
    LayoutParams.MATCH_PARENT,
    LayoutParams.MATCH_PARENT);
contentLayout.gravity = Gravity.CENTER;
textView.setText(R.string.test);

Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/arial.ttf");
textView.setTypeface(tf);

layout.addView(textView, contentLayout);

The problem I'm having is that either does not gravity work or match_parent. The texts ends up in the upper right corner and not in the center as it does on the xml version.

Community
  • 1
  • 1

1 Answers1

1

In the XML you're setting the gravity of the text inside the TextView. In the code you are setting the TextView's layout gravity.

To replicate what you've done in the XML, change the line:

contentLayout.gravity = Gravity.CENTER;

to:

textView.setGravity(Gravity.CENTER);

If your XML had android:layout_gravity="center" instead of android:gravity="center" then your code would match as it is.

nmw
  • 6,664
  • 3
  • 31
  • 32
  • Thank you! I never would have figured that one out. Does this mean that the TextView is actually filling up the whole screen? I thought that LayoutParams.FILL_PARENT would do that. I thought that the TextView was centered in the layout, but now i think that the TextView fills upp the whole parent and then centers the text inside of the TextView, am I correct? – Mikael Berglund Jan 09 '13 at 16:59
  • 1
    Exactly right. I find it helps when starting off creating a layout to set background colour on all Views - to see exactly where everything is and how big they are. And by the way, FILL_PARENT and MATCH_PARENT are exactly the same. – nmw Jan 09 '13 at 17:22