实例代码
public class MainActivity extends Activity {
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
super.onStart();
tv.post(new Runnable() {
@Override
public void run() {
int width = tv.getMeasuredWidth();
int height = tv.getMeasuredHeight();
}
});
ViewTreeObserver observer = tv.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
tv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = tv.getMeasuredWidth();
int height = tv.getMeasuredHeight();
}
});
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus){
int width = tv.getMeasuredWidth();
int height = tv.getMeasuredHeight();
}
}
int widthMeasureSpec=MeasureSpec.makeMeasureSpec(MeasureSpec.EXACTLY, measuredWidth);
int heightMeasureSpec=MeasureSpec.makeMeasureSpec(MeasureSpec.AT_MOST, 1000);
tv.measure(widthMeasureSpec, heightMeasureSpec);
int measuredHeight2 = tv.getMeasuredHeight();
}