jason
jason

Reputation: 7164

How to use margins and gravity at the same time for TextView

I'm generating TextViews like this :

for(String substring : list)
{
   TextView myTv = new TextView(this);
   myTv.setTextSize(20);
   myTv.setGravity(Gravity.CENTER);
   myTv.setText(substring);
}

This works perfectly, except I want more space between TextViews (TextViews are below each other). So I changed my code to this to set bottom margin :

for(String substring : list)

    {
       TextView myTv = new TextView(this);
       myTv.setTextSize(20);
       LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(AbsListView.LayoutParams.WRAP_CONTENT, AbsListView.LayoutParams.WRAP_CONTENT);
       llp.setMargins(0, 0, 0, 30);
       myTv.setLayoutParams(llp);
       myTv.setGravity(Gravity.CENTER);
       myTv.setText(substring);
    }

Now I have margins between TextViews but now all TextView are aligned to left. How can I have space between TextViews and have TextViews centered? Thanks.

Upvotes: 0

Views: 173

Answers (2)

tiny sunlight
tiny sunlight

Reputation: 6251

for(String substring : list)

{
   TextView myTv = new TextView(this);
   myTv.setTextSize(20);
   LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(AbsListView.LayoutParams.WRAP_CONTENT, AbsListView.LayoutParams.WRAP_CONTENT);
   llp.setMargins(0, 0, 0, 30);
   //notice this line.
   llp.gravity = Gravity.CENTER;
   myTv.setLayoutParams(llp);
   myTv.setGravity(Gravity.CENTER);
   myTv.setText(substring);
}

Upvotes: 1

Boban S.
Boban S.

Reputation: 1662

It is easier to control views in XML.

You can create text_view.xml layout file with the text view you want. And then inflate it later how many times you want.

text_view.xml

<TextView
    android:layout_widht="match_parent"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:layout_marginBottom="30dp"
    android:gravity="center"
    ... />

In your activity/fragment

TextView textView = (TextView) LayoutInflater.from(context).inflate(new LinearLayout(context), R.layout.text_view, false);
textView.setText("some text");

Upvotes: 0

Related Questions