簡體   English   中英

如何在android中獲取textView的寬度

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

這是我正在使用的代碼......

<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的寬度和高度。

試試這樣:

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

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

如果你需要在繪制視圖之前獲得寬度,高度,那么你可以這樣做

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