首页 > 解决方案 > Android getLocationonScreen() 函数返回父视图的位置而不是子视图

问题描述

我在我的活动中创建了一个RelativeLayout,并且我正在使用addView 和RelativeLayout.LayoutParams 动态创建我添加到RelativeLayout 的ImageView 对象。然后当我去获取子视图的位置时,它总是返回父视图的坐标。以下是代码的相关部分:

public class MainActivity extends AppCompatActivity {
    public RelativeLayout parentLayout;
    RelativeLayout.LayoutParams layoutParams;
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        parentLayout = findViewById(R.id.parentRelativeLayout);
    }

    // Method to dynamically add the ImageView to the parent
    public int addObject(Drawable drawing, int x, int y) {
        ImageView newObj = new ImageView(getApplicationContext());
        newObj.setBackground(drawing);
        layoutParams = new RelativeLayout.LayoutParams(50, 50);
        layoutParams.leftMargin = x;
        layoutParams.topMargin = y;
        int childIndex = parentLayout.getChildCount()-1;
        parentLayout.addView(newObj, childIndex,layoutParams);

        return childIndex;
    }

    public int[] getChildLocation(int childIndex) {
        View childView;
        int[] outlineCoord = new int[2];

        childView = parentLayout.getChildAt(childIndex);
        childView.getLocationOnScreen(outlineCoord);

        return outlineCoord;
    }

}

如果我然后添加一个子视图并尝试检索子视图的坐标,我总是会得到父视图的位置:

childIndex = addObject(getResources().getDrawable(blackcircle), 100, 200);
outlineCoord = getChildLocation(childIndex);

Log.i("LOC:", "Location of child is X: " + outlineCoord[0] + " Y: " + outlineCoord[1]);

我无法弄清楚我在这里做错了什么。

标签: androidandroid-layoutandroid-view

解决方案


推荐阅读