第一种方法:
TextView<span style="font-family: Arial, Helvetica, sans-serif;">=new TextView(this);</span>
textview.getViewTreeObserver().addOnGlobalLayoutListener(new onGlobalLayoutListener(){
public void onGlobalLayout(){
textview.getViewTreeObserver().removeGlobalOnLayoutListener(this);
textview.getHeight();
textview.getWidght();
}
})
第二种方法:
textview.post(new Runnable{
public void run(){
textview.getHeight();
}
})
下面是全部代码:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
public class TestLPActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_lp);
final TextView tv = (TextView) findViewById(R.id.tv);
// LayoutParams layoutParams = (LayoutParams) tv.getLayoutParams();
// layoutParams.height = 200;
// layoutParams.width = 200;
// tv.setLayoutParams(layoutParams);
// System.out.println("layoutParams.height:" + layoutParams.height + "layoutParams.width:"
// + layoutParams.width);
// tv.measure(0, 0);
// int measuredHeight = tv.getMeasuredHeight();
// int measuredWidth = tv.getMeasuredWidth();
// System.out.println("measuredHeight:" + measuredHeight + "measuredWidth:" + measuredWidth);
// tv.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
// @Override
// public void onGlobalLayout() {
// // 结论: 如果布局文件里宽高配置 match_parent, wrap_content, LayoutParams就是 -1, -2.
// // 无论什么时候都是
// System.out.println(tv.getHeight());
// System.out.println(tv.getLayoutParams().width+" "+tv.getLayoutParams().height);
// RelativeLayout.LayoutParams lp = (LayoutParams) tv.getLayoutParams();
// lp.height = 500;
// tv.setLayoutParams(lp);
// System.out.println(tv.getLayoutParams().width+" "+tv.getLayoutParams().height);
// tv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
// }
// });
tv.post(new Runnable() {
@Override
public void run() {
System.out.println(tv.getHeight());
System.out.println(tv.getLayoutParams().width+" "+tv.getLayoutParams().height);
RelativeLayout.LayoutParams lp = (LayoutParams) tv.getLayoutParams();
lp.height = 500;
tv.setLayoutParams(lp);
System.out.println(tv.getLayoutParams().width+" "+tv.getLayoutParams().height);
}
});
}
}