Search code examples
androidlayoutviewgravitylayoutparams

Android: center Textview in extended Layout


Can I somehow prevent calling the Layout method of all Children if I only want to set the layout for the parent view and still want to keep the layout settings of the children?

Currently I call parent.layout() and all its children get a width and heiht of zero. Can't I somehow set the children to FillParent istead of setting the layout to ALL ? :-(

By the way, my parent is an extended LinearLayout containing mostly Textviews.



Edit: Some code:

myLayout extends LinearLayout

myLayout.layout(left, top, right, bottom);                
myLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1));

for each child in myLayout do {
  child.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
  if (v instanceof TextView) {
    ((TextView) v).setGravity(Gravity.CENTER);
  }

But child still has:
left: 0 top: 0 right: 0 bottom: 0

Edit 2: By the way: the code above is insider the onLayout method of a ViewGroup.


Solution

  • Your child views aren't getting measured (since you don't call their layout()), so the system still thinks that they are 0x0px.

    Android uses a 2-pass system of measure/layout.

    Check out the developer docs to see how the drawing/layout sequence happens: http://developer.android.com/guide/topics/ui/how-android-draws.html

    You might want to try calling their layout(), then setting the height/width on the children, then calling requestLayout().

    Hope that helps.