cj1098
cj1098

Reputation: 1610

How to center a textView with java code inside a linear layout

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.

Upvotes: 1

Views: 3096

Answers (1)

Blundell
Blundell

Reputation: 76574

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)!

Upvotes: 1

Related Questions