Pergunta

I need to measure a linear layout after I add an item to it dynamically (after inflating it). I tried both getHeight and getMeasuredHeight in onStart and in onCreate but they're returning 0. One solution I can think of is to measure the inflated items' heights, and add them. But I hope there's a more legit solution.

Thanks

Foi útil?

Solução

On Honeycomb and later, you can add an OnLayoutChangeListener to the view.

Prior to Honeycomb, you would have to use an OnGlobalLayoutListener. This is a bit trickier because it gets called for the entire layout, not just the view you specified, so typically you would register it, then unregister it the first time it is called.

linearLayout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    public void onGlobalLayout() {
        linearLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        // do the rest of your stuff here
    }
});

Until there is a measure/layout pass, the reported size of the view will be zero.

Outras dicas

you have to wait until it is drawn. You can post a runnable in the root's layout and when it is invoked you should be able to retrieve the height/weight of the child

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top