Android如何获取通过编程方式创建的视图的宽度

21

我有一个通过编程创建的TextView,像这样:

                TextView mTextView = new TextView(getApplicationContext());

                final LayoutParams params = new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                ((MarginLayoutParams) params).setMargins(8, 8, 0, 0);

                mTextView.setText(mText);
                mTextView.setLayoutParams(params);
                mTextView.setPadding(2, 2, 2, 2);
                mTextView.setBackground(getResources().getDrawable(R.drawable.note_corps));

                tagMap.addView(mTextView);

                textViewsWidth = mTextView.getWidth();

但是mTextView.getWidth()始终返回0。

如果我尝试:

mTextView.getLayoutParams().width

它返回LayoutParams类中对应值(-1或-2)的LayoutParams参数

我该如何获取视图的宽度?

编辑 我需要在这里做到这一点:

            @Override
        public void onPostExecute(Hashtable<String, Integer> hash){
            final ScrollView tagMapScroll = (ScrollView) findViewById(R.id.tagMapScroll);
            final LinearLayout tagMap = (LinearLayout) findViewById(R.id.tagMap);
            final ArrayList<Integer> arr = new ArrayList<Integer>(hash.values());
            final Enumeration<String> e = hash.keys();
            int index = 0;
            int textViewsWidth = 0;

            while(e.hasMoreElements()){
                final TextView tV = new TextView(getApplicationContext());

                tV.setTextColor(Color.parseColor("#666666"));
                tV.setText(Html.fromHtml(randomColor() + e.nextElement()));
                tV.setTextSize(arr.get(index));

                final LayoutParams params = new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                ((MarginLayoutParams) params).setMargins(8, 8, 0, 0);

                tV.setLayoutParams(params);
                tV.setPadding(2, 2, 2, 2);
                tV.setBackground(getResources().getDrawable(R.drawable.note_corps));

                tagMap.addView(tV);

                textViewsWidth += tV.getWidth();

                index++;
            }

            tagMapScroll.setVisibility(ScrollView.VISIBLE);

        }

修改解决方案 我使用了来自@androiduser答案的这个:

mTextView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
                int width = mTextView.getMeasuredWidth();
                int height = mTextView.getMeasuredHeight();

问题已解决!


1
只有在视图的 onMeasure 方法被调用后,才能获取视图的宽度。参考:https://dev59.com/e3A65IYBdhLWcg3w2yo2 - Amulya Khare
现在,如果您告诉我们您需要宽度的原因,也许有人可以提出一个解决方案。 - Amulya Khare
您正在过早地调用getWidth()方法。UI界面尚未在屏幕上进行大小调整和布局。 - Siddharth_Vyas
如果任何答案有帮助,请标记为正确答案以关闭该线程:D - Diego Palomar
编辑,我需要为多个TextView(可能有数百个)执行此操作,并在onPostExecute()中完成。 - Pumpkin
我试图在onPost方法中获取已消失视图的高度, 我尝试添加OnGlobalLayoutListener,但我的已消失视图的高度仍然为0。 但是你的解决方案非常有效。但是,各位,如果想了解这个主题,可以阅读以下答案:[1] https://dev59.com/aW445IYBdhLWcg3w0ddD [2] https://dev59.com/rFPTa4cB1Zd3GeqPjXVh - Eren Utku
5个回答

17

我使用了这个解决方案:

yourView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {
        // Ensure you call it only once
        yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this);

        // Here you can get the size :)
    }
});

你会怎么称呼它?我刚刚添加了width = mTextView.getWidth(),但不起作用。 - Pumpkin
2
检查一下,也许你漏掉了什么:http://www.sherif.mobi/2013/01/how-to-get-widthheight-of-view.html - Siddharth_Vyas

4

获取方式:

tV.post(new Runnable() {
                    @Override
                    public void run() {
                        int width=tV.getMeasuredWidth();
                    }
                });

2

对于FILL_PARENT和WRAP_CONTENT,它们的值是恒定不变的。如果您想要检查视图大小,可以尝试以下方法:

tagMap.addView(mTextView);
tagMap.post(new Runnable() {
                    @Override
                    public void run() {
                        mTextView. getWidth();
                    }
                });

你必须等待安卓绘制完TextView。这样,你就可以在tagMap队列中发布一个Runnable,在文本视图被绘制之后执行它(这样应该会有宽度和高度)。


我需要在将视图添加到tagMap后立即获得其宽度,但是我无法成功,当我制作提示时它仍为0。 - Pumpkin

1
在这种方法中,您可以获取视图的宽度和高度。
    @Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    int width = mTextView.getWidth();
    int height = mTextView.getHeight();
}

并将 TextView mTextView 定义为全局变量


0
你需要使用ViewTreeObserver类来注册监听器,以便在视图树中出现全局更改时可以得到通知。这些全局事件包括但不限于整个树的布局、绘制过程的开始、触摸模式的更改。
在Activity的onCreate方法中添加以下代码:
ViewTreeObserver vto = mTextView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        mTextView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        int viewWidth = mTextView.getMeasuredWidth();

    }
});

比我正确,而且更快。 :) - Enrichman
我需要在onPostExecute()中完成这个任务。 - Pumpkin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接