首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

怎么在onCreate中获取TextView的宽度

2013-10-11 
如何在onCreate中获取TextView的宽度在onCreate()里是获取不到控件的width,height的,这个时候控件都没有me

如何在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;    }});

热点排行