在Android中如何获得它被设置为WRAP_CONTENT TextView的宽度设置为、宽度、如何获得、Android

2023-09-06 10:23:41 作者:散场的拥抱つ

我想添加一个文本,为我所设置宽度为WRAP_CONTENT TextView的。我试图让这个TextView的宽度。但它显示出0在所有的情况下。我怎样才能得到TextView的宽度设置文本后。

I am trying to add a text to the textview for which i have set the width as Wrap_content. I am trying to get the width of this textview. But its showing 0 in all the cases. How Can i get the width of the textview after setting the text into it.

在code是因为:

        LinearLayout ll= new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        TextView tv = new TextView(this);
        tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
        ll.addView(tv);
        tv.setText("Hello 1234567890-0987654321qwertyuio787888888888888888888888888888888888888888888888888");
        System.out.println("The width is == "+tv.getWidth());// result is 0
        this.setContentView(ll);

请建议。 先谢谢了。

推荐答案

与动态宽/高访问量得到他们正确的尺寸只有在布局过程完成之后(http://developer.android.com/reference/android/view/View.html#Layout). 您可以OnLayoutChangeListener添加到您的TextView,并得到它的尺寸有:

Views with the dynamic width/height get their correct size only after a layout process was finished (http://developer.android.com/reference/android/view/View.html#Layout). You can add OnLayoutChangeListener to your TextView and get it's size there:

tv.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
           public void onLayoutChange(View v, int left, int top, int right, int bottom, 
                                      int oldLeft, int oldTop, int oldRight, int oldBottom) {
                        final int width = right - left;
                        System.out.println("The width is == " + width);                
    });