1

So I want to center a text View inside a linear layout where I have 2 other objects that populate the linear layout. I have a imageView and another textView. How would I go about centering the textView so the text is in the middle of the screen? This is what I have so far.

View linearLayout = findViewById(R.id.rockLayout);
        ImageView mineralPicture = new ImageView(this);
        TextView mineralName = new TextView(this);
        TextView mineralProperties = new TextView(this);
        mineralProperties.setText("The properties are: " + Statics.rockTable.get(rockName).getDistinctProp());
        mineralProperties.setId(2);
        mineralName.setText("This mineral is: " + rockName);
        mineralName.setGravity(Gravity.CENTER);
        mineralName.setId(1);
        mineralName.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
        mineralProperties.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
        mineralPicture.setId(3);
        mineralPicture.setImageResource(R.drawable.rocks);
        mineralPicture.setAdjustViewBounds(true);
        mineralPicture.setMaxHeight(100);
        mineralPicture.setMaxWidth(200);
        mineralPicture.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));


        ((LinearLayout)linearLayout).addView(mineralName);
        ((LinearLayout)linearLayout).addView(mineralProperties);
        ((LinearLayout)linearLayout).addView(mineralPicture);

I should mention I've tried doing such things as mineralName.setGravtiy(Gravity.CENTER); and it hasn't worked.

cj1098
  • 1,560
  • 6
  • 32
  • 60
  • 1
    a) let the textview match_parent on the width and use gravity center b) on the textview layout params set the layout_gravity to center (sorry for the terms I normally do this in XML)! – Blundell May 10 '12 at 21:06
  • that answered my question. post it as an answer and I'll accept! – cj1098 May 10 '12 at 21:08

1 Answers1

1

a) let the textview match_parent on the width and use gravity center

b) on the textview layout params set the layout_gravity to center (sorry for the terms I normally do this in XML)!

Blundell
  • 75,855
  • 30
  • 208
  • 233