【问题标题】:how to get the width of textView in android如何在android中获取textView的宽度
【发布时间】:2018-03-20 20:25:46
【问题描述】:

这是我正在使用的代码...

<TextView
    android:id="@+id/textView"
    android:layout_width="100dp"
    android:layout_height="40dp"
    android:text="AMIT KUMAR" />

这是一个java代码。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView textView = (TextView) findViewById(R.id.textView);
    Log.d("left", textView.getLeft() + " " + textView.getRight() + " "
            + textView.getWidth()+" "+textView.getHeight());
}

对于以上所有,我得到的输出是 0。

那么如何获取 textView 的宽度和高度。

【问题讨论】:

标签: android textview


【解决方案1】:

试试这样:

textView.setText("GetHeight");
textView.measure(0, 0);       //must call measure!
textView.getMeasuredHeight(); //get height
textView.getMeasuredWidth();  //get width

【讨论】:

  • 这是我在 SO 中找到的最佳答案。
  • 像魅力一样工作。感谢您的简短而中肯的回答。
  • 哈利路亚!我支持 Rahul Mandaliya 关于这是我在 Stack Overflow 上找到的最佳答案的评论。 +1
【解决方案2】:

在您的 onCreate 上执行此操作,您将获得 textView 的实际 widthheight

textView.postDelayed(new Runnable() {

            @Override
            public void run() {
                textView.invalidate();
                float dw = textView.getWidth();
                float dh = textView.getHeight();                
                Log.v("",dw + " - " + dh);              
            }
        }, 1);  

如果您需要在绘制视图之前获取宽度、高度,那么您可以这样做

ViewTreeObserver viewTreeObserver = textView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @SuppressLint("NewApi")
        @SuppressWarnings("deprecation")
        @Override
        public void onGlobalLayout() {
            float dw = textView.getWidth();
            float dh = textView.getHeight();

            System.out.print(dw +" - "+dh);


            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                textView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            } else {
                textView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        }

    });

【讨论】:

  • 是的,我得到了答案,但请您解释一下为什么要使用此代码。表示可运行线程
  • 在布局发生之前,runnable 不会运行。所以它会等到视图显示在屏幕上,因此它总是会给出正确的宽度、高度。但是如果您需要在绘制视图之前计算宽度高度,它将失败。
猜你喜欢
  • 2013-04-07
  • 2021-06-04
  • 2015-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多