Java Code Examples for android.view.ViewTreeObserver#addOnGlobalLayoutListener()

The following examples show how to use android.view.ViewTreeObserver#addOnGlobalLayoutListener() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LabelView.java    From labelview with Apache License 2.0 8 votes vote down vote up
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);
            }
        });

    }
 
Example 2
Source File: MediaStreamLayout.java    From api-samples with MIT License 8 votes vote down vote up
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();
            }
        }
    });
}
 
Example 3
Source File: StickHeaderViewPager.java    From StickyHeaderViewPager with Apache License 2.0 6 votes vote down vote up
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();
            }
        }
    });
}
 
Example 4
Source File: CropView.java    From ImagePicker with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 5
Source File: NewsActivity.java    From Slide with GNU General Public License v3.0 6 votes vote down vote up
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();
                }
            });
        }
    }
}
 
Example 6
Source File: ToolbarColorizeHelper.java    From Slide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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);
        }
    });
}
 
Example 7
Source File: ScrollUtils.java    From MVPAndroidBootstrap with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
        }
    });
}
 
Example 8
Source File: PEWTextView.java    From ParallaxEverywhere with MIT License 5 votes vote down vote up
@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();
}
 
Example 9
Source File: PhotoViewAttacher.java    From light-novel-library_Wenku8_Android with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example 10
Source File: PhotoViewAttacher.java    From Dashboard with MIT License 5 votes vote down vote up
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);
}
 
Example 11
Source File: ReviewAndConfirmActivity.java    From px-android with MIT License 5 votes vote down vote up
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);
        }
    });
}
 
Example 12
Source File: UserInfoActivity.java    From nono-android with GNU General Public License v3.0 5 votes vote down vote up
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);
        }
    });

}
 
Example 13
Source File: TextViewOverflowing.java    From TextViewOverflowing with MIT License 5 votes vote down vote up
@Override
public void setText(CharSequence text, BufferType type) {
    super.setText(text, type);

    ViewTreeObserver vto = getViewTreeObserver();
    vto.addOnGlobalLayoutListener(this);
}
 
Example 14
Source File: VodDisplayActivity.java    From KSYMediaPlayer_Android with Apache License 2.0 5 votes vote down vote up
@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;
    }
}
 
Example 15
Source File: DocActivityView.java    From Mupdf with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 16
Source File: AppActivityLifecycleCallbacks.java    From sa-sdk-android with Apache License 2.0 5 votes vote down vote up
/**
 * 注册 ViewTreeObserver
 */
private void registerViewTreeObserver(Activity activity) {
    ViewTreeObserver viewTreeObserver = activity.getWindow().getDecorView().getViewTreeObserver();
    viewTreeObserver.addOnGlobalFocusChangeListener(AppViewTreeObserver.getInstance());
    viewTreeObserver.addOnGlobalLayoutListener(AppViewTreeObserver.getInstance());
    viewTreeObserver.addOnScrollChangedListener(AppViewTreeObserver.getInstance());
}
 
Example 17
Source File: PhotoViewAttacher.java    From Android with MIT License 4 votes vote down vote up
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);
}
 
Example 18
Source File: PhotoViewAttacher.java    From AndroidPickPhotoDialog with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example 19
Source File: CommentUserPreviewDialog.java    From Capstone-Project with MIT License 4 votes vote down vote up
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);
            }
        }
    });
}
 
Example 20
Source File: FullscreenPopupWindow.java    From Noyze with Apache License 2.0 4 votes vote down vote up
@Override
public void onAttachedToWindow() {
    super.onAttachedToWindow();
    ViewTreeObserver vto = mLayout.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(this);
}