获取相对ImageView的位置以编程方式筛选 [英] Get position of ImageView relative to screen programmatically

查看:118
本文介绍了获取相对ImageView的位置以编程方式筛选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编程让我的的ImageView的位置。通过位置,我的意思是从屏幕上方的的ImageView在像素的距离。我已经试过张贴在计算器所有其他解决方案,但它不是为我工作。我的最低API级别为8。

这些都是codeS我曾尝试 -

  ImageView的形象=(ImageView的)findViewById(R.id.imageView1);
1)image.getTop();

2)私人诠释getRelativeTop(查看MyView的){
    如果(myView.getParent()== myView.getRootView())
        返回myView.getTop();
    其他
        返回myView.getTop()+ getRelativeTop((查看)myView.getParent());
}

3)image.getLocationOnScreen(INT [] locaiton);
 

解决方案

您需要等待回调时布局一直放在与孩子的意见。这就是你需要添加到您的根视图,以便计算出坐标图像的监听器。否则返回0。

  getViewTreeObserver()。addOnGlobalLayoutListener(新OnGlobalLayoutListener(){
    公共无效onGlobalLayout(){
        。getViewTreeObserver()removeGlobalOnLayoutListener(本);

        INT []位置=新INT [2];
        image.getLocationOnScreen(位置);
        INT X =位置[0];
        INT Y =位置[1];
    }
});
 

I want to get the position of my ImageView programmatically. By position, I mean the distance in pixel from top of the screen to that ImageView. I have tried every other solution posted in stackoverflow but it's not working for me. My minimum API level is 8.

These are the codes I have tried-

ImageView image = (ImageView) findViewById(R.id.imageView1);
1) image.getTop();

2) private int getRelativeTop(View myView) {
    if (myView.getParent() == myView.getRootView())
        return myView.getTop();
    else
        return myView.getTop() + getRelativeTop((View) myView.getParent());
}

3) image.getLocationOnScreen(int[] locaiton);

解决方案

You need to wait for the callback when the layout has been placed with children views. This is the listener you need to add to your root view in order to calculate the coordinates for your image. Otherwise it will return 0.

getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    public void onGlobalLayout() {
        getViewTreeObserver().removeGlobalOnLayoutListener(this);

        int[] locations = new int[2];
        image.getLocationOnScreen(locations);
        int x = locations[0];
        int y = locations[1];
    }
});

这篇关于获取相对ImageView的位置以编程方式筛选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆