0

When a user clicks a button on my main view, I inflate a new view and add it to my main view. My new view contains a TextView with the default text of "HelloWorld", while setting up the view I setText("You have just come from...") and I getLeft() and getRight() on my textview. Problem is, it's returning coordinates as if the text was still "HelloWorld".

I think it's probably doing this because the updated text hasn't been drawn yet. But if I click a button in this new view and in onClick do the getLeft() and getRight(), it works correctly. What am I doing wrong?

Roger
  • 4,249
  • 10
  • 42
  • 60

2 Answers2

1

I think you could create a class for your view and then override View.onFinishInflate and do your stuff there.

Should be a really short class, with only this method overridden.

Alternatively, you could use the solution suggested here: ViewGroup finish inflate event But the downside is that you will get called back each time the layout is redone or updated, not only after inflate.

Community
  • 1
  • 1
Marcel N.
  • 13,726
  • 5
  • 47
  • 72
-1

here's a way to do this without extending or overriding anything:

private static void runJustBeforeBeingDrawn(final View view, final Runnable runnable)
{
    final ViewTreeObserver vto = view.getViewTreeObserver();
    final OnPreDrawListener preDrawListener = new OnPreDrawListener()
    {
        @Override
        public boolean onPreDraw()
        {
            runnable.run();
            final ViewTreeObserver vto = view.getViewTreeObserver();
            vto.removeOnPreDrawListener(this);
            return true;
        }
    };
    vto.addOnPreDrawListener(preDrawListener);
}

in the runnable parameter , you can get the updated size and position and everything else that you need.

alternatively , you can use addOnGlobalLayoutListener instead of addOnPreDrawListener if you wish.

EDIT: Alternative to runJustBeforeBeingDrawn: https://stackoverflow.com/a/28136027/878126

android developer
  • 114,585
  • 152
  • 739
  • 1,270