1

How may I know how many child views may I programmatically add to a horizontal oriented LinearLayout?

I tried something like this:

for (int i = 0; i < listSize; i++) {
            View childView = getChildView(parentView); // method that returns an inflated View from a xml layout
            if (parentView.getChildCount() > 0 && childView.getWidth() > parentView.getWidth() - parentView.getPaddingRight() - parentView
                    .getChildAt(parentView.getChildCount()-1)
                    .getRight()) {
                break;
            }

            parentView.addView(childView);
        }

but it seems like it doesn't work. Any ideas are much appreciated.

EDIT: It adds only one child to that LinearLayout, although it clearly looks like that should be enough space to add at least one more. After logging those variables used in the 'if' condition, it looks like parent.getWidth, and parentView.getChildAt(...).getRight() returns 0.

DoruAdryan
  • 1,314
  • 3
  • 20
  • 35
  • Please explain what "it seems like it doesn't work" means. – CommonsWare May 25 '15 at 21:32
  • It adds only one child to that LinearLayout, although it clearly looks like that should be enough space to add at least one more. After logging those variables used in the 'if' condition, it looks like parent.getWidth, and parentView.getChildAt(...).getRight() returns 0. – DoruAdryan May 25 '15 at 21:35
  • Put that into the original question, not everyone reads comments – Bojan Kseneman May 25 '15 at 21:37
  • 2
    Also all those methods return 0 until the views are not yet drawn, you either need an observer to know when that happens or manually measure it – Bojan Kseneman May 25 '15 at 21:40
  • @BojanKseneman ok, I used an onPreDrawListener on parentView, and I managed to use getMeasuredWidth on parentView. Now the problem is getting lastChildView.getRight and the width of the View that is about to be added, so I can manage to compare: parent.getWidth - lastChild.getRight with newView.getWidth. Do I need to use listeners for these too? It would look so awful :-) – DoruAdryan May 26 '15 at 11:56

0 Answers0