android - 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]);
我无法弄清楚我在这里做错了什么。
解决方案
推荐阅读
- hyperledger-fabric - Hyperledger Fabric: Channel configuration has no channels defined
- vb.net - 从 "[1_5],[1_3],[1_5]" 到 "5,3,5" 的字符串操作
- node.js - dockerized express 应用程序:npm-debug 仅在搬运工中显示
- php - 使用 phpspreadsheet 将 HTML 导出到 Excel
- react-native - 如何从 React 项目中的 jest-junit 获取代码覆盖率报告
- python - python通过路径获取xml元素
- python - Expotential growth of symbols in python?
- objective-c - 未找到 libstdc++.6.0.9 的库未找到 xcode 11.1
- r - gsub替换包含尾随空格的子字符串不起作用
- postgresql - psql:Unix域套接字“/var/run/postgresql/.s.PGSQL.5432”上的连接?