0

My Activity layout has View, i have get Y position this view at the beginning of the program, but if i shall insert in bottom method onCreate , i get position value = 0. How i can know, when view is drawn and get her Y position. I try get Y position when i click on button, position get good, but i have get position without using the button.

I get position:

private float cardsStartPosition = 0;
if (cardsStartPosition == 0) {
    cardsStartPosition = commonCardContainer.getY();
}

Thanks for answer.

bvv
  • 1,893
  • 3
  • 14
  • 16

3 Answers3

2

Try this method..It works fine for me.

ViewTreeObserver vto = YourView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {

        //do your stuff here                    

        }
    });
Ketan Ahir
  • 6,678
  • 1
  • 23
  • 45
1

Add a global layout listener to your view, you will get notified when layout is done and your view has dimensions ...

    view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {

            //Here you can get your dimensions
            int width = view.getWidth();
            //View.removeOnGlobalLayoutListener(this);

        }

    });
ElDuderino
  • 3,253
  • 2
  • 21
  • 38
0

You mention just View. So if that means it's your custom view, you can override the onLayout():

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
  ...;
}

This way you can observe any layout changes of your view. If you're also interested in size changes, there's also the onSizeChanged():

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
  ...;
}

If it's not your custom view, I'd go with the Ketan Ahir's way.

Sufian
  • 6,405
  • 16
  • 66
  • 120
tomorrow
  • 1,260
  • 1
  • 14
  • 26