2015年11月9日 星期一

Get the view's height when the views are not built in onCreate(), onStart(), or onResume()

Reference:
http://stackoverflow.com/questions/4142090/how-do-you-to-retrieve-dimensions-of-a-view-getheight-and-getwidth-always-r/4406090#4406090
http://stackoverflow.com/questions/8170915/getheight-returns-0-for-all-android-ui-objects
http://www.eoeandroid.com/thread-240677-1-1.html?_dsign=f73765c1

Code snippet:
private ViewTreeObserver mViewTreeObserver;
private TextView mTextView;
protected void onCreate(Bundle savedInstanceState) {
    .........
    mTextView = (TextView) findViewById(R.id.my_text_view);
    mViewTreeObserver = mTextView.getViewTreeObserver();
    mViewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {                      
                        int height = mTextView.getHeight();
                        if(!mViewTreeObserver.isAlive()){
                            mViewTreeObserver = mNewTrackingRelativeLayout.getViewTreeObserver();
                        }
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            mViewTreeObserver.removeOnGlobalLayoutListener(this);
                        } else {
                            mViewTreeObserver.removeGlobalOnLayoutListener(this);
                        }
                    }
                });
    .........
}


沒有留言: