Search code examples
androidview

Android get view location on screen


in the project, I tried adding a View object dynamically in a RelativeLayout

    ImageView card = new ImageView(this);
    card.setImageResource(R.drawable.card);
    RelativeLayout.LayoutParams layoutParams =
            new RelativeLayout.LayoutParams(225, 315);
    layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    layoutParams.rightMargin = 40;
    parent.addView(card, layoutParams);

after a while, when I tried to get the location of this View, no method works. As I found in Studio's debug view, the View's layoutparams and all its attrs like mLeft... got the value 0.

So how could I solve the problem? thanks a lot.


Solution

  • It might be because you tried to get position before onLayout has happened.

    You might try something like this:

    ViewTreeObserver vto=view.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
    @Override public void onGlobalLayout(){
        int [] location = new int[2];
        view.getLocationOnScreen(location);
        x = location[0];
        y = location[1];
        view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
    }
    

    Also check how to get view's position in coordinates?