TextView gravity
Asked Answered
K

1

12

Has anyone tried to write his own implementation of ViewGroup with some TextViews in it?

I have a problem, that TextViews in such an implementation don't respect the gravity property TextView.setGravity(Gravity.CENTER) and text is positioned in the top left corner.

Can anyone help me find out why?

EDIT:

Ok. nevermind, I figured it out on my own already.

If enyone is interested, I just overwrote method onMeasure() (for all my TextViews) and changed call from super.onMeasure() to setMeasuredDimension(int, int) and gravity started to work normally.

Basically, in my custom layout I use the following class to display text:

private static class GravityTextView extends TextView {  

    public GravityTextView(Context context) {  
        super(context);  
    }

    @Override  
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);  
    }

}
Kame answered 10/11, 2010 at 15:22 Comment(2)
Thanks for sharing! A note, I had to call measure from onLayout on the TextViews too. So overriding onMeasure as above and calling measure.Milestone
try to set gravity of linear/relative layoutPirri
M
3

This is not the wrong behavior you are just trying to set the wrong property.

With TextView.setGravity(Gravity.CENTER) you are setting the gravity of the TextView's content.

What you are looking for is the layout_gravity.

Megadeath answered 10/11, 2010 at 16:30 Comment(1)
This is exactly what I am trying to do. If, for example, my TextView is in some random location in my custom Layout, and it's taking up 200px of space, and text inside it only 50px, I want that text to be aligned in the center of that TextView (so TextView will still keep it's 200px space, but the text will be in the middle of it, making it 75px marging between TextView borders and actual text).Kame

© 2022 - 2024 — McMap. All rights reserved.