Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 437
DixieFlatline Avatar asked Jan 27 '11 16:01

DixieFlatline


1 Answers

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);
like image 162
Kevin Coppock Avatar answered Sep 18 '22 21:09

Kevin Coppock