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

1

7

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.

Balbur answered 27/1, 2011 at 16:19 Comment(0)
O
14

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);
Ostrom answered 27/1, 2011 at 16:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.