如何在onCreate中获取TextView的宽度

在onCreate()里是获取不到控件的width,height的,这个时候控件都没有measure,layout完毕,所以获取到的结果都是0。要获取控件的宽度、高度必须在measure、layout过程完毕之后。
有2种方法:
1.如lss所讲的一样:
ViewTreeObserver vto = mBtnSend.getViewTreeObserver();
    
  vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
  @Override
  public void onGlobalLayout() {
  int height = mBtnSend.getMeasuredHeight();
  int width = mBtnSend.getMeasuredWidth();
  System.out.println("height:" + height + "  " + "width:" + width);
  }  
  });

2.在Activity里重写方法
  public void onWindowFocusChanged(boolean hasFocus);

  在窗口第一次获得焦点的时候,肯定能获取到控件的width,height。



3.

textView.getViewTreeObserver().addOnPreDrawListener( new  OnPreDrawListener() {
 
             public  boolean  onPreDraw() {
         //这里textView已经初始化完毕,你可以得到所有属性
             return  true ;
     }
});

你可能感兴趣的:(如何在onCreate中获取TextView的宽度)