在 Android 中如何获取设置为 Wrap_Content 的 Textview 的宽度 [英] In Android how to get the width of the Textview which is set to Wrap_Content

查看:19
本文介绍了在 Android 中如何获取设置为 Wrap_Content 的 Textview 的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将文本添加到我已将其宽度设置为 Wrap_content 的文本视图中.我正在尝试获取此文本视图的宽度.但它在所有情况下都显示为 0.将文本设置为文本视图后,如何获取文本视图的宽度.

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.

代码如下:

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

请提出建议.提前致谢.

Please suggest. Thanks in advance.

推荐答案

具有动态宽度/高度的视图只有在布局过程完成后才能获得正确的大小(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);                
    });

这篇关于在 Android 中如何获取设置为 Wrap_Content 的 Textview 的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆