how to get view's position in coordinates?

2019-07-04 21:17发布

问题:

Hi I have an ImageView inside RelativeLayout, now how can I get X and Y position of imageview on screen ?

I have tried

getLocationOnScreen
log(mPhoto.getLeft());
log(mPhoto.getScrollX());
log(mPhoto.getX());
log(mPhoto.getTranslationX());

but all of them returns 0.

Above functions are called after progmatically setting imageview to center

    RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(mFaceWidth, mFaceHeight);
    lp1.addRule(RelativeLayout.CENTER_HORIZONTAL);
    lp1.addRule(RelativeLayout.CENTER_VERTICAL);
    mPhoto.setLayoutParams(lp1);
    mPhoto.requestLayout();

回答1:

View Tree Observer callback will be called after the view has been rendered on screen. Above methods will always yield 0 as view/layout has not been rendered yet.

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);

}
}


回答2:

Try this

view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i("trace", "Y: " + v.getY());
        }
    });

Clicking the image view will print visual Y position of view in logcat.



回答3:

try this :

int [] location = new int[2];
view.getLocationOnScreen(location);
x = location[0];
y = location[1];


回答4:

It was not yet measured so I used following How can you tell when a layout has been drawn?

final LinearLayout layout = (LinearLayout)findViewById(R.id.YOUR_VIEW_ID);
ViewTreeObserver vto = layout.getViewTreeObserver(); 
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
        this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
        int width  = layout.getMeasuredWidth();
        int height = layout.getMeasuredHeight(); 
        int x = layout.getX();
        int y = layout.getY();

    } 
});