-
StackOverflow 文档
-
Android 教程
-
获取计算的视图尺寸
-
计算活动中的初始视图尺寸
package com.example;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
public class ExampleActivity extends Activity {
@Override
protected void onCreate(@Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
final View viewToMeasure = findViewById(R.id.view_to_measure);
// viewToMeasure dimensions are not known at this point.
// viewToMeasure.getWidth() and viewToMeasure.getHeight() both return 0,
// regardless of on-screen size.
viewToMeasure.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
// viewToMeasure is now measured and laid out, and displayed dimensions are known.
logComputedViewDimensions(viewToMeasure.getWidth(), viewToMeasure.getHeight());
// Remove this listener, as we have now successfully calculated the desired dimensions.
viewToMeasure.getViewTreeObserver().removeOnPreDrawListener(this);
// Always return true to continue drawing.
return true;
}
});
}
private void logComputedViewDimensions(final int width, final int height) {
Log.d("example", "viewToMeasure has width " + width);
Log.d("example", "viewToMeasure has height " + height);
}
}