简体   繁体   English

如何在android中获取textView的宽度

[英]how to get the width of textView in android

This is the code what i am using... 这是我正在使用的代码......

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

and here is a java code. 这是一个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());
}

for all above i am getting the output 0. 对于以上所有我得到输出0。

so how can i get the width and height of textView. 那我怎样才能得到textView的宽度和高度。

Try like this: 试试这样:

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

On your onCreate do this then you will get actual width and height of the textView onCreate上执行此操作,您将获得textView的实际宽度高度

textView.postDelayed(new Runnable() {

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

If you need to get width, height before view drawn then you can do this 如果你需要在绘制视图之前获得宽度,高度,那么你可以这样做

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);
            }
        }

    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM