Setting margin and gravity of textview in code doesn't work

DixieFlatline picture DixieFlatline · Jan 27, 2011 · Viewed 21.2k times · Source

If i set only margin for my textview, that is inside linear layout, everything works. If i set only gravity for my textview, it works. But if i set both attributes (gravity and margins), gravity remains left with margins set successfully.

My code for setting both attributes that doesnt work as expected:

tv2=new TextView(this);
tv2.setText("Text");
LinearLayout.LayoutParams para=new LinearLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT );
para.setMargins(0, 10, 0, 10); //left,top,right, bottom
tv2.setLayoutParams(para);
tv2.setGravity(android.view.Gravity.CENTER_HORIZONTAL);

I must build my layout in code, can't use xml files.

Answer

Kevin Coppock picture Kevin Coppock · Jan 27, 2011

Try using this instead:

para.gravity = Gravity.CENTER_HORIZONTAL;
tv2.setLayoutParams(para);

//the below sets the view's content gravity, not the gravity
//of the view itself. Since the width is wrap_content, this
//has no effect.
//tv2.setGravity(android.view.Gravity.CENTER_HORIZONTAL);