获取相对ImageView的位置以编程方式筛选位置、方式、ImageView

2023-09-05 07:58:46 作者:余生颓废

我想编程让我的的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);
 

解决方案 HTml简单问题,相对地址和绝对地址的问题啊

您需要等待回调时布局一直放在与孩子的意见。这就是你需要添加到您的根视图,以便计算出坐标图像的监听器。否则返回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];
    }
});