addOnGlobalLayoutListener ( )源码实例Demo

android.view.ViewTreeObserver#addOnGlobalLayoutListener ( )源码实例Demo

下面列出了android.view.ViewTreeObserver#addOnGlobalLayoutListener ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: labelview   文件: LabelView.java
public void setTargetView(View target, int distance, Gravity gravity) {

        if (!replaceLayout(target)) {
            return;
        }

        final int d = dip2Px(distance);
        final Gravity g = gravity;
        final View v = target;

        ViewTreeObserver vto = getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                getViewTreeObserver().removeGlobalOnLayoutListener(this);
                calcOffset(getMeasuredWidth(), d, g, v.getMeasuredWidth(), false);
            }
        });

    }
 
源代码2 项目: api-samples   文件: MediaStreamLayout.java
public void onOrientationChange() {
    ViewTreeObserver observer = getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (lastWidth != getWidth() || lastHeight != getHeight()) {
                if (Build.VERSION.SDK_INT < 16) {
                    getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
                resizeAllVideo();
            }
        }
    });
}
 
源代码3 项目: Slide   文件: ToolbarColorizeHelper.java
/**
 * It's important to set overflowDescription atribute in styles, so we can grab the reference
 * to the overflow icon. Check: res/values/styles.xml
 *
 * @param activity
 * @param colorFilter
 */
private static void setOverflowButtonColor(final Activity activity, final PorterDuffColorFilter colorFilter) {
    final String overflowDescription = activity.getString(R.string.abc_action_menu_overflow_description);
    final ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
    final ViewTreeObserver viewTreeObserver = decorView.getViewTreeObserver();
    viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            final ArrayList<View> outViews = new ArrayList<>();
            decorView.findViewsWithText(outViews, overflowDescription,
                    View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
            if (outViews.isEmpty()) {
                return;
            }
            ImageView overflow = (ImageView) outViews.get(0);
            overflow.setColorFilter(colorFilter);
            removeOnGlobalLayoutListener(decorView, this);
        }
    });
}
 
源代码4 项目: Slide   文件: NewsActivity.java
private void scrollToTabAfterLayout(final int tabIndex) {
    //from http://stackoverflow.com/a/34780589/3697225
    if (mTabLayout != null) {
        final ViewTreeObserver observer = mTabLayout.getViewTreeObserver();

        if (observer.isAlive()) {
            observer.dispatchOnGlobalLayout(); // In case a previous call is waiting when this call is made
            observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    mTabLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    mTabLayout.getTabAt(tabIndex).select();
                }
            });
        }
    }
}
 
源代码5 项目: ImagePicker   文件: CropView.java
public CropView(Context context, AttributeSet attrs, int defStyleAttr)
{
    super(context, attrs, defStyleAttr);

    setScaleType(ScaleType.MATRIX);

    mDragScaleDetector = VersionedGestureDetector.newInstance(context, this);
    mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener());
    mGestureDetector.setOnDoubleTapListener(new DefaultOnDoubleTapListener());

    outlinePaint.setAntiAlias(true);
    outlinePaint.setColor(highlightColor);
    outlinePaint.setStyle(Paint.Style.STROKE);
    outlinePaint.setStrokeWidth(dpToPx(OUTLINE_DP));
    outsidePaint.setARGB(125, 50, 50, 50);

    ViewTreeObserver observer = getViewTreeObserver();
    if (null != observer)
    {
        observer.addOnGlobalLayoutListener(this);
    }
}
 
private void initStickHeaderViewHight() {
    final ViewTreeObserver vto = mStickheader.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            mStickHeaderHeight = mStickheader.getMeasuredHeight();
            mStickViewHeight = mStickheader.getChildAt(1).getMeasuredHeight();
            if (mStickHeaderHeight > 0 && mStickViewHeight > 0) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    mStickheader.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    mStickheader.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
                updateChildViewHight();
            }
        }
    });
}
 
源代码7 项目: nono-android   文件: UserInfoActivity.java
private void setUpCollapsed(){
    collapsingToolbarLayout.setBackgroundColor(bgColor);
    collapsingToolbarLayout.setContentScrimColor(bgColor);
    collapsingToolbarLayout.setStatusBarScrimColor(colorBurn(bgColor));
    final AppBarLayout appbar = (AppBarLayout) findViewById(R.id.app_bar);
    ViewTreeObserver vto=collapsingToolbarLayout.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if(Build.VERSION.SDK_INT>=16){
                collapsingToolbarLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }else {
                collapsingToolbarLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
            float heightDp = getResources().getDisplayMetrics().heightPixels - 48 * getResources().getDisplayMetrics().density;
            if (collapsingToolbarLayout.getMeasuredHeight() > heightDp) {
                CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) appbar.getLayoutParams();
                lp.height = (int) (collapsingToolbarLayout.getMeasuredHeight() + 48 * getResources().getDisplayMetrics().density);
                tabLayout.requestLayout();
            }
        }
    });
    collapsingToolbarLayout.setCollapsedTitleTextColor(Color.TRANSPARENT);
    collapsingToolbarLayout.setExpandedTitleColor(Color.TRANSPARENT);
    collapsingToolbarLayout.setOnListener(new MyCollapsingToolbarLayout.OnListener() {
        @Override
        public void collapsed() {
            findViewById(R.id.header).setVisibility(View.INVISIBLE);
            collapsingToolbarLayout.setCollapsedTitleTextColor(Color.WHITE);
        }

        //
        @Override
        public void expand() {
            findViewById(R.id.header).setVisibility(View.VISIBLE);
            collapsingToolbarLayout.setCollapsedTitleTextColor(Color.TRANSPARENT);
        }
    });

}
 
/**
 * 注册 ViewTreeObserver
 */
private void registerViewTreeObserver(Activity activity) {
    ViewTreeObserver viewTreeObserver = activity.getWindow().getDecorView().getViewTreeObserver();
    viewTreeObserver.addOnGlobalFocusChangeListener(AppViewTreeObserver.getInstance());
    viewTreeObserver.addOnGlobalLayoutListener(AppViewTreeObserver.getInstance());
    viewTreeObserver.addOnScrollChangedListener(AppViewTreeObserver.getInstance());
}
 
源代码9 项目: Mupdf   文件: DocActivityView.java
public void start(final String path)
{
	started = false;

	((Activity)getContext()).getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
	((Activity)getContext()).getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

	//  inflate the UI
	final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	final LinearLayout view = (LinearLayout) inflater.inflate(R.layout.doc_view, null);

	final ViewTreeObserver vto = getViewTreeObserver();
	vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
	{
		@Override
		public void onGlobalLayout()
		{
			if (!started)
			{
				findViewById(R.id.tabhost).setVisibility(mShowUI?View.VISIBLE:View.GONE);
				findViewById(R.id.footer).setVisibility(mShowUI?View.VISIBLE:View.GONE);
				afterFirstLayoutComplete(path);

				started = true;
			}
		}
	});

	addView(view);
}
 
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    WindowManager.LayoutParams params = getWindow().getAttributes();
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (landscape_content.getVisibility() == View.VISIBLE) {
                    landscape_content.setVisibility(View.GONE);
                    hideStatusBar();
                    isPanelShowing_Landscape = false;
                }
            }
        }, 5000);
        params.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setAttributes(params);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        showLandscapePanel();
        ViewTreeObserver vto2 = content.getViewTreeObserver();
        vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                content.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                full_screen_height = content.getHeight();
                full_screen_width = content.getWidth();
            }
        });
        currentState = 1;
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        params.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setAttributes(params);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        showPortraitPanel();
        Display.setLight(this, currentBrighrness, this.getWindow().getAttributes());
        full_screen_height = 0;
        full_screen_width = 0;
        currentState = 0;
    }
}
 
源代码11 项目: TextViewOverflowing   文件: TextViewOverflowing.java
@Override
public void setText(CharSequence text, BufferType type) {
    super.setText(text, type);

    ViewTreeObserver vto = getViewTreeObserver();
    vto.addOnGlobalLayoutListener(this);
}
 
源代码12 项目: MVPAndroidBootstrap   文件: ScrollUtils.java
/**
 * Add an OnGlobalLayoutListener for the view.
 * This is just a convenience method for using {@code ViewTreeObserver.OnGlobalLayoutListener()}.
 * This also handles removing listener when onGlobalLayout is called.
 *
 * @param view     the target view to add global layout listener
 * @param runnable runnable to be executed after the view is laid out
 */
public static void addOnGlobalLayoutListener(final View view, final Runnable runnable) {
    ViewTreeObserver vto = view.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            } else {
                view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
            runnable.run();
        }
    });
}
 
源代码13 项目: px-android   文件: ReviewAndConfirmActivity.java
private void addScrollBottomPadding(final View floatingConfirmLayout, final View scrollView) {
    final ViewTreeObserver floatingObserver = floatingConfirmLayout.getViewTreeObserver();
    floatingObserver.addOnGlobalLayoutListener(() -> {
        final int bottomPadding = floatingConfirmLayout.getHeight();
        if (scrollView.getPaddingBottom() != bottomPadding) {
            scrollView.setPadding(scrollView.getPaddingLeft(), scrollView.getPaddingTop(),
                scrollView.getPaddingRight(), bottomPadding);
        }
    });
}
 
源代码14 项目: Dashboard   文件: PhotoViewAttacher.java
public PhotoViewAttacher(ImageView imageView) {
    mImageView = new WeakReference<ImageView>(imageView);

    imageView.setOnTouchListener(this);

    ViewTreeObserver observer = imageView.getViewTreeObserver();
    if (null != observer)
        observer.addOnGlobalLayoutListener(this);

    // Make sure we using MATRIX Scale Type
    setImageViewScaleTypeMatrix(imageView);

    if (imageView.isInEditMode()) {
        return;
    }
    // Create Gesture Detectors...
    mScaleDragDetector = VersionedGestureDetector.newInstance(
            imageView.getContext(), this);

    mGestureDetector = new GestureDetector(imageView.getContext(),
            new GestureDetector.SimpleOnGestureListener() {

                // forward long click listener
                @Override
                public void onLongPress(MotionEvent e) {
                    if (null != mLongClickListener) {
                        mLongClickListener.onLongClick(getImageView());
                    }
                }
            });

    mGestureDetector.setOnDoubleTapListener(this);

    // Finally, update the UI so that we're zoomable
    setZoomable(true);
}
 
public PhotoViewAttacher(ImageView imageView) {
    mImageView = new WeakReference<ImageView>(imageView);

    imageView.setDrawingCacheEnabled(true);
    imageView.setOnTouchListener(this);

    ViewTreeObserver observer = imageView.getViewTreeObserver();
    if (null != observer)
        observer.addOnGlobalLayoutListener(this);

    // Make sure we using MATRIX Scale Type
    setImageViewScaleTypeMatrix(imageView);

    if (imageView.isInEditMode()) {
        return;
    }
    // Create Gesture Detectors...
    mScaleDragDetector = VersionedGestureDetector.newInstance(
            imageView.getContext(), this);

    mGestureDetector = new GestureDetector(imageView.getContext(),
            new GestureDetector.SimpleOnGestureListener() {

                // forward long click listener
                @Override
                public void onLongPress(MotionEvent e) {
                    if (null != mLongClickListener) {
                        mLongClickListener.onLongClick(getImageView());
                    }
                }
            });

    mGestureDetector.setOnDoubleTapListener(new DefaultOnDoubleTapListener(this));

    // Finally, update the UI so that we're zoomable
    setZoomable(true);
}
 
源代码16 项目: ParallaxEverywhere   文件: PEWTextView.java
@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();

    mOnScrollChangedListener = new ViewTreeObserver.OnScrollChangedListener() {
        @Override
        public void onScrollChanged() {
            applyParallax();
        }
    };

    mOnGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            heightView = (float) getHeight();
            widthView = (float) getWidth();

            applyParallax();
        }
    };

    ViewTreeObserver viewTreeObserver = getViewTreeObserver();
    viewTreeObserver.addOnScrollChangedListener(mOnScrollChangedListener);
    viewTreeObserver.addOnGlobalLayoutListener(mOnGlobalLayoutListener);

    if (updateOnDraw
            && android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        onDrawListener = new ViewTreeObserver.OnDrawListener() {
            @Override
            public void onDraw() {
                applyParallax();
            }
        };
        viewTreeObserver.addOnDrawListener(onDrawListener);
    }

    parallaxAnimation();
}
 
源代码17 项目: Noyze   文件: FullscreenPopupWindow.java
@Override
public void onAttachedToWindow() {
    super.onAttachedToWindow();
    ViewTreeObserver vto = mLayout.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(this);
}
 
private void setContent(Comment comment) {
    txtUsernameAlternate.setText(getContext().getString(R.string.dialog_comment_user_preview_username_alternative,
            comment.getUsernameAlternative()));
    txtUsername.setText(comment.getUsername());
    txtUserHeadline.setText(comment.getUserHeadline());
    txtCommentBody.setText(Html.fromHtml(comment.getBody()));

    // Modify link clicks on textview
    BetterLinkMovementMethod method = BetterLinkMovementMethod.linkify(Linkify.ALL,
            txtCommentBody);
    method.setOnLinkClickListener(new BetterLinkMovementMethod.OnLinkClickListener() {
        @Override
        public boolean onClick(TextView textView, String s) {
            CustomTabsHelperFragment.open(getOwnerActivity(),
                    mCustomTabsIntent,
                    Uri.parse(s),
                    mCustomTabsFallback);
            return true;
        }
    });

    // Set uer image.
    String userImageUrl = comment.getUserImageThumbnailUrl();
    userImageUrl = ImageUtils.getCustomCommentUserImageThumbnailUrl(userImageUrl,
            ScreenUtils.dpToPxInt(getContext(), 44),
            ScreenUtils.dpToPxInt(getContext(), 44));
    imgViewUser.setImageURI(userImageUrl);

    // Hide headline text if headline is empty.
    txtUserHeadline.setVisibility(TextUtils.isEmpty(comment.getUserHeadline()) ?
            View.GONE : View.VISIBLE);

    // Set extra details.
    String extraDetails = String.format("%s \u2022 %s",
            getContext().getResources().getQuantityString(R.plurals.item_post_details_comment_votes,
                    comment.getVotes(),
                    comment.getVotes()),
            getContext().getString(getStringResourceIdForTimeUnit(comment.getTimeUnit()),
                    comment.getTimeAgo()));
    txtCommentExtraDetails.setText(extraDetails);

    final ViewTreeObserver observer = scrollViewCommentContent.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @SuppressLint("LongLogTag")
        @Override
        public void onGlobalLayout() {
            int viewHeight = scrollViewCommentContent.getMeasuredHeight();
            int contentHeight = relativeLayoutCommentContent.getHeight();
            Logger.d(TAG, "viewHeight: " + viewHeight + " ; contentHeight: " + contentHeight);
            if (viewHeight  - contentHeight < 0) {
                // Scrollable.
                Logger.d(TAG, "View is scrollable.");
                viewDivider.setVisibility(View.VISIBLE);
                relativeLayoutCommentContent.setPadding(0,
                        0,
                        0,
                        ScreenUtils.dpToPxInt(getContext(), 8));
            } else {
                Logger.d(TAG, "View is not scrollable.");
                viewDivider.setVisibility(View.GONE);
                relativeLayoutCommentContent.setPadding(0,
                        0,
                        0,
                        0);
            }
        }
    });
}
 
源代码19 项目: AndroidPickPhotoDialog   文件: PhotoViewAttacher.java
public PhotoViewAttacher(ImageView imageView, boolean zoomable) {
    mImageView = new WeakReference<>(imageView);

    imageView.setDrawingCacheEnabled(true);
    imageView.setOnTouchListener(this);

    ViewTreeObserver observer = imageView.getViewTreeObserver();
    if (null != observer)
        observer.addOnGlobalLayoutListener(this);

    // Make sure we using MATRIX Scale Type
    setImageViewScaleTypeMatrix(imageView);

    if (imageView.isInEditMode()) {
        return;
    }
    // Create Gesture Detectors...
    mScaleDragDetector = VersionedGestureDetector.newInstance(
            imageView.getContext(), this);

    mGestureDetector = new GestureDetector(imageView.getContext(),
            new GestureDetector.SimpleOnGestureListener() {

                // forward long click listener
                @Override
                public void onLongPress(MotionEvent e) {
                    if (null != mLongClickListener) {
                        mLongClickListener.onLongClick(getImageView());
                    }
                }

                @Override
                public boolean onFling(MotionEvent e1, MotionEvent e2,
                                       float velocityX, float velocityY) {
                    if (mSingleFlingListener != null) {
                        if (getScale() > DEFAULT_MIN_SCALE) {
                            return false;
                        }

                        if (MotionEventCompat.getPointerCount(e1) > SINGLE_TOUCH
                                || MotionEventCompat.getPointerCount(e2) > SINGLE_TOUCH) {
                            return false;
                        }

                        return mSingleFlingListener.onFling(e1, e2, velocityX, velocityY);
                    }
                    return false;
                }
            });

    mGestureDetector.setOnDoubleTapListener(new DefaultOnDoubleTapListener(this));
    mBaseRotation = 0.0f;

    // Finally, update the UI so that we're zoomable
    setZoomable(zoomable);
}
 
源代码20 项目: Android   文件: PhotoViewAttacher.java
public PhotoViewAttacher(ImageView imageView, boolean zoomable) {
    mImageView = new WeakReference<>(imageView);

    imageView.setDrawingCacheEnabled(true);
    imageView.setOnTouchListener(this);

    ViewTreeObserver observer = imageView.getViewTreeObserver();
    if (null != observer)
        observer.addOnGlobalLayoutListener(this);

    // Make sure we using MATRIX Scale Type
    setImageViewScaleTypeMatrix(imageView);

    if (imageView.isInEditMode()) {
        return;
    }
    // Create Gesture Detectors...
    mScaleDragDetector = VersionedGestureDetector.newInstance(
            imageView.getContext(), this);

    mGestureDetector = new GestureDetector(imageView.getContext(),
            new GestureDetector.SimpleOnGestureListener() {

                // forward long click listener
                @Override
                public void onLongPress(MotionEvent e) {
                    if (null != mLongClickListener) {
                        mLongClickListener.onLongClick(getImageView());
                    }
                }

                @Override
                public boolean onFling(MotionEvent e1, MotionEvent e2,
                                       float velocityX, float velocityY) {
                    if (mSingleFlingListener != null) {
                        if (getScale() > DEFAULT_MIN_SCALE) {
                            return false;
                        }

                        if (MotionEventCompat.getPointerCount(e1) > SINGLE_TOUCH
                                || MotionEventCompat.getPointerCount(e2) > SINGLE_TOUCH) {
                            return false;
                        }

                        return mSingleFlingListener.onFling(e1, e2, velocityX, velocityY);
                    }
                    return false;
                }
            });

    mGestureDetector.setOnDoubleTapListener(new DefaultOnDoubleTapListener(this));
    mBaseRotation = 0.0f;

    // Finally, update the UI so that we're zoomable
    setZoomable(zoomable);
}