如何在Oncreate中获取TextView的宽度?

2025-04-30 21:22:45
推荐回答(4个)
回答1:

  在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。

回答2:

oncreate的时候,view还没有初始化完, view的 onLayout 方法里才知道大小,所以你可以 override view的onLayout ,在那里获得宽高。

回答3:

我找到解决方法了,请参考。LayoutParams tvPara = (LayoutParams) m_tv.getLayoutParams(); m_tv.requestLayout(); m_iTextWidth = tvPara.width;

回答4:

Add this to your activity's onCreateViewTreeObserver vto = layout.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { You should be able to get the width and height over here. layout.getViewTreeObserver().removeGlobalOnLayoutListener(this); } });