Android get programmatically created view's width

前端 未结 5 2112
一生所求
一生所求 2021-02-18 16:48

I have TextView created programmatically, like that:

                TextView mTextView = new TextView(getApplicationContext());

                final LayoutPar         


        
相关标签:
5条回答
  • 2021-02-18 17:28

    I used this solution:

    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 :)
        }
    });
    
    0 讨论(0)
  • 2021-02-18 17:29

    You have to use ViewTreeObserver class which is used to register listeners that can be notified of global changes in the view tree. Such global events include, but are not limited to, layout of the whole tree, beginning of the drawing pass, touch mode change.

    In the Activity's onCreate mehotd put this:

    ViewTreeObserver vto = mTextView.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            mTextView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            int viewWidth = mTextView.getMeasuredWidth();
    
        }
    });
    
    0 讨论(0)
  • 2021-02-18 17:31

    In this method you can get the width height of the view..

        @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        int width = mTextView.getWidth();
        int height = mTextView.getHeight();
    }
    

    and define TextView mTextView as global

    0 讨论(0)
  • 2021-02-18 17:32

    get this way:

    tV.post(new Runnable() {
                        @Override
                        public void run() {
                            int width=tV.getMeasuredWidth();
                        }
                    });
    
    0 讨论(0)
  • 2021-02-18 17:35

    those values are constant value for FILL_PARENT and WRAP_CONTENT. If you want to check the view size you can try this way:

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

    you have to wait until android draws the TextView. This way you are posting a Runnable in the tagMap queue, that is executed, hopefully after the textview is draw (so it should be weight and height)

    0 讨论(0)
提交回复
热议问题