001 Activity/View#onWindowFocusChanged
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus){
int width = needSizeView.getWidth();
int height = needSizeView.getHeight();
}
}
002 view.post(runnable)
@Override
protected void onStart() {
super.onStart();
view.post(new Runnable() {
@Override
public void run() {
int width = needSizeView.getWidth();
int height = needSizeView.getHeight();
}
});
}
003 ViewTreeObserver
@Override
protected void onStart() {
super.onStart();
ViewTreeObserver viewTreeObserver = needSizeView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = needSizeView.getWidth();
int height = needSizeView.getHeight();
}
});
}
004 view.measure(int widthMeasureSpec,int heightMeasureSpec)
正确使用的两种方式:
- 具体的数值 dp/px
int widthMeasureSpec = MeasureSpec.makeMeasure(100,MeasureSpec.EXACTLY);
int heightMeasureSpec = MeasureSpec.makeMeasure(100,MeasureSpec.EXACTLY);
needSizeView.measure(widthMeasureSpec,heightMeasureSpec);
- wrap_content
int widthMeasureSpec = MeasureSpec.makeMeasure((1<<30)-1,MeasureSpec.AT_MOST);
int heightMeasureSpec = MeasureSpec.makeMeasure((1<<30)-1,MeasureSpec.AT_MOST);
needSizeView.measure(widthMeasureSpec,heightMeasureSpec);