我知道在 UI 设置之前我无法太早获取尺寸。
我知道我必须在 onCreate() 之后获取尺寸。
但即使我执行以下操作,他们仍然总是返回 0。
onCreate():
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_path);
...
onCreateDone = true;
}
希望在onSensorChanged()中获取尺寸
// called when sensor values change
public void onSensorChanged(SensorEvent event) { // is roughly called 350 times in 1s
if (layoutSizeNotObtained && onCreateDone) { // only runs once to get the layout size
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.activity_show_path_relativelayout);
int layoutWidth = relativeLayout.getWidth();
int layoutHeight = relativeLayout.getHeight();
Log.d("ShowPathActivity", "layout size: " + layoutWidth + " " + layoutHeight);
Constant.setInitialX(layoutWidth / 2);
Constant.setInitialY(layoutHeight / 2);
layoutSizeNotObtained = false;
}
....
}
哪里出了问题?
最佳答案
问题是没有保证,布局是在 onSensorChanged(SensorEvent event)
调用期间完成的。仅在第一次布局期间测量 View ,并且在 onCreate()
之后一段时间测量,而不是在其期间或之后立即测量。
我建议使用this suggestion通过 ViewTreeObserver .
关于android - 即使在 onCreate() 之后,布局尺寸仍然返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17646537/