我需要获取布局内某些视图的坐标。我尝试做喜欢(在onCreateView内)
TextView[] tv = new TextView[3]
tv[0] = (TextView) view.findViewById(R.id.content0);
tv[1] = (TextView) view.findViewById(R.id.content1);
tv[2] = (TextView) view.findViewById(R.id.content2);
RectF[] positions = new RectF[3];
for (int i = 0; i < tv.length; i++) {
int top = tv[i].getTop();
int left = tv[i].getLeft();
int width = tv[i].getWidth();
int height = tv[i].getHeight();
positions[i] = new RectF(left, top, left + width, top + height);
}
但是,如果我尝试将位置数组打印到Logcat中,则始终获得0,0,0,0。怎么了?
最佳答案
正如blackbelt所述,您必须等待视图的布局才能获取尺寸。
使用一个ViewTreeObserver。
getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
for (int i = 0; i < tv.length; i++) {
int top = tv[i].getTop();
int left = tv[i].getLeft();
int width = tv[i].getWidth();
int height = tv[i].getHeight();
positions[i] = new RectF(left, top, left + width, top + height);
}
getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
关于android - fragment 内的 View 坐标始终为null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21756223/