在Activity的OnCreate中,即使是在setContent之后 我们也是没有办法获取到控件 例如TextView 的 长和高。
是因为,在OnCreate中,控件并没有初始化绘制出来,所以get到的width 及 height 是 0。
解决的办法的代码如下:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.txt);
// wrongMethod(tv);
firstMethod(tv);
// secondMethod(tv);
// thirdMethod(tv);
}
/**
* 此方法有误,由于TextView都没有measure,layout完毕 也就是TextView都没有绘制完毕 所以 get到的
* width,height 都是 0
*
* @param tv
*/
private void wrongMethod(final TextView tv) {
int width = tv.getWidth();
int height = tv.getHeight();
System.out.println("----wrong-----" + "height:" + height + " "
+ "width:" + width);
}
/**
* 方法一
* @param tv
*/
private void firstMethod(final TextView tv) {
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int height = tv.getMeasuredHeight();
int width = tv.getMeasuredWidth();
System.out.println("----first-----" + "height:" + height + " "
+ "width:" + width);
setTextSize(tv, width, height);
}
});
}
/**
* 方法二
* @param tv
*/
private void secondMethod(final TextView tv) {
tv.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
public boolean onPreDraw() {
// 这里textView已经初始化完毕,你可以得到所有属性
int width = tv.getHeight();
int height = tv.getWidth();
System.out.println("----second-----" + "height:" + height + " "
+ "width:" + width);
setTextSize(tv, width, height);
return true;
}
});
}
/**
* 方法三
* @param tv
*/
private void thirdMethod(final TextView tv) {
int intw = View.MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
int inth = View.MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
tv.measure(intw, inth);
int width = tv.getMeasuredWidth();
int height = tv.getMeasuredHeight();
System.out.println("----third-----" + "height:" + height + " "
+ "width:" + width);
setTextSize(tv, width, height);
}
/**
* 根据获取到的 width和 height 来重新设置 TextView 的 宽和高
*
* @param tv
* @param width
* @param height
*/
private void setTextSize(TextView tv, int width, int height) {
int size = (height > width) ? height : width;
tv.setWidth(size);
tv.setHeight(size);
}
}
改变前:
改变后: