Android get programmatically created view's width

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

I have TextView created programmatically, like that:

                TextView mTextView = new TextView(getApplicationContext());

                final LayoutPar         


        
5条回答
  •  执念已碎
    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();
    
        }
    });
    

提交回复
热议问题