Example usage for android.view ViewTreeObserver addOnGlobalLayoutListener

List of usage examples for android.view ViewTreeObserver addOnGlobalLayoutListener

Introduction

In this page you can find the example usage for android.view ViewTreeObserver addOnGlobalLayoutListener.

Prototype

public void addOnGlobalLayoutListener(OnGlobalLayoutListener listener) 

Source Link

Document

Register a callback to be invoked when the global layout state or the visibility of views within the view tree changes

Usage

From source file:Main.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
 *//*from w w  w  .  j  a  v  a  2 s. c  o  m*/
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();
        }
    });
}

From source file:Main.java

/**
 * Add an OnGlobalLayoutListener for the view.
 * <p>This is just a convenience method for using {@code ViewTreeObserver.OnGlobalLayoutListener()}.
 * This also handles removing listener when onGlobalLayout is called.</p>
 *
 * @param view     The target view to add global layout listener.
 * @param runnable Runnable to be executed after the view is laid out.
 *//*from  w w w  .  jav  a 2s .c  o  m*/
public static void addOnGlobalLayoutListener(final View view, final Runnable runnable) {
    ViewTreeObserver vto = view.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @SuppressWarnings("deprecation")
        @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();
        }
    });
}

From source file:com.getkeepsafe.taptargetview.ViewUtil.java

/** Executes the given {@link java.lang.Runnable} when the view is laid out **/
static void onLaidOut(final View view, final Runnable runnable) {
    if (isLaidOut(view)) {
        runnable.run();//  w  w  w .  ja v a  2  s  . c  om
        return;
    }

    final ViewTreeObserver observer = view.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            final ViewTreeObserver trueObserver;

            if (observer.isAlive()) {
                trueObserver = observer;
            } else {
                trueObserver = view.getViewTreeObserver();
            }

            removeOnGlobalLayoutListener(trueObserver, this);

            runnable.run();
        }
    });
}

From source file:despotoski.nikola.github.com.bottomnavigationlayout.Util.java

public static void runOnAttachedToLayout(View v, final Runnable runnable) {
    if (ViewCompat.isLaidOut(v))
        runnable.run();//  www .j av a2s . c o  m
    else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            v.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
                @TargetApi(Build.VERSION_CODES.HONEYCOMB)
                @Override
                public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft,
                        int oldTop, int oldRight, int oldBottom) {
                    runnable.run();
                    v.removeOnLayoutChangeListener(this);
                }
            });
            return;
        }

        final ViewTreeObserver viewTreeObserver = v.getViewTreeObserver();
        if (viewTreeObserver != null && viewTreeObserver.isAlive()) {
            viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    runnable.run();
                    if (viewTreeObserver.isAlive())
                        //noinspection deprecation
                        viewTreeObserver.removeGlobalOnLayoutListener(this);
                }
            });
        }
    }
}

From source file:Main.java

/**
 * Make a textview to a collapsible textview with the indicator on the right of the textview
 * //from w ww  .j a  v a  2  s.  c  om
 * @param tv , {@link TextView} to be converted
 * @param upDrawableResId , drawable resource id to be used as up indicator
 * @param downDrawableResId , drawable resource id to be used as down indicator
 * @param lineTreshold , no of line to be displayed for the collapsed state
 */
public static void makeCollapsible(final TextView tv, int upDrawableResId, int downDrawableResId,
        final int lineTreshold) {

    final Drawable[] drawables = tv.getCompoundDrawables();
    final Drawable up = tv.getContext().getResources().getDrawable(upDrawableResId);
    final Drawable down = tv.getContext().getResources().getDrawable(downDrawableResId);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        tv.setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1], down, drawables[3]);
        tv.setEllipsize(TruncateAt.END);
        tv.setMaxLines(lineTreshold);
        tv.setTag(true);
        tv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (v instanceof TextView) {
                    TextView tv = (TextView) v;
                    boolean snippet = (Boolean) tv.getTag();
                    if (snippet) {
                        // show everything
                        snippet = false;
                        tv.setMaxLines(Integer.MAX_VALUE);
                        tv.setEllipsize(null);
                        tv.setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1], up,
                                drawables[3]);
                    } else {
                        // show snippet
                        snippet = true;
                        tv.setMaxLines(lineTreshold);
                        tv.setEllipsize(TruncateAt.END);
                        tv.setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1], down,
                                drawables[3]);
                    }
                    tv.setTag(snippet);
                }

            }
        });
    } else {
        tv.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable arg0) {

                ViewTreeObserver vto = tv.getViewTreeObserver();
                vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

                    @SuppressWarnings("deprecation")
                    @SuppressLint("NewApi")
                    @Override
                    public void onGlobalLayout() {

                        tv.setEllipsize(TruncateAt.END);
                        int line = tv.getLineCount();
                        tv.setMaxLines(lineTreshold);
                        if (line <= lineTreshold) {
                            tv.setOnClickListener(new View.OnClickListener() {

                                @Override
                                public void onClick(View arg0) {
                                    // empty listener
                                    // Log.d("line count", "count: "+
                                    // tv.getLineCount());
                                }
                            });
                            if (tv.getLayout() != null) {
                                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                                    tv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                                } else {
                                    tv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                                }
                            }
                            return;
                        }

                        tv.setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1], down,
                                drawables[3]);
                        tv.setTag(true);
                        tv.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                if (v instanceof TextView) {
                                    TextView tv = (TextView) v;
                                    boolean snippet = (Boolean) tv.getTag();
                                    if (snippet) {
                                        snippet = false;
                                        // show everything
                                        tv.setMaxLines(Integer.MAX_VALUE);
                                        tv.setEllipsize(null);
                                        tv.setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1],
                                                up, drawables[3]);
                                    } else {
                                        snippet = true;
                                        // show snippet
                                        tv.setMaxLines(lineTreshold);
                                        tv.setEllipsize(TruncateAt.END);
                                        tv.setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1],
                                                down, drawables[3]);
                                    }
                                    tv.setTag(snippet);
                                }

                            }
                        });

                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                            tv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        } else {
                            tv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        }
                    }

                });
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

        });
    }

}

From source file:com.agenmate.lollipop.util.ViewUtils.java

public static void waitForLayoutPrepared(final View view, final LayoutPreparedListener listener) {
    final ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
    if (viewTreeObserver != null) {
        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override//ww w .  j a va 2s  . c o  m
            public void onGlobalLayout() {
                invokeLayoutListener();
                removeGlobalOnLayoutListenerIfNeeded();
            }

            private void invokeLayoutListener() {
                if (listener != null) {
                    listener.onLayoutPrepared(view);
                }
            }

            private void removeGlobalOnLayoutListenerIfNeeded() {
                final ViewTreeObserver laterViewTreeObserver = view.getViewTreeObserver();
                if (laterViewTreeObserver != null && laterViewTreeObserver.isAlive()) {
                    laterViewTreeObserver.removeGlobalOnLayoutListener(this);
                }
            }
        });
    }
}

From source file:Main.java

private static void expandInner(final View view, final View parentView, final ViewGroup rootContainer,
        final int targtetHeight) {

    setHeight(view, 0);//from  w ww .ja  v a  2 s.  c  om
    view.setVisibility(View.VISIBLE);
    final Animation animation = new Animation() {

        private final Rect rect = new Rect();
        private final Rect parentVisibleRect = new Rect();

        ViewTreeObserver.OnGlobalLayoutListener globalLayoutListener;

        private final Runnable checkViewRunnable = new Runnable() {
            @Override
            public void run() {
                checkForViewInsideVisibleArea();
            }
        };

        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {

            int neededHeight = interpolatedTime == 1 ? LayoutParams.WRAP_CONTENT
                    : (int) (targtetHeight * interpolatedTime);
            setHeight(view, neededHeight);

            final ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();

            if (globalLayoutListener == null) {
                globalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {

                    @Override
                    public void onGlobalLayout() {

                        if (globalLayoutListener == null) {
                            removeGlobalLayoutListener(viewTreeObserver, this);
                        }

                        checkForViewInsideVisibleArea();
                    }
                };

                viewTreeObserver.addOnGlobalLayoutListener(globalLayoutListener);
            }

            if (globalLayoutListener != null && interpolatedTime == 1) {
                runInUIThread(checkViewRunnable);
                globalLayoutListener = null;
            }

            view.requestLayout();
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }

        private void checkForViewInsideVisibleArea() {

            if (rootContainer.indexOfChild(parentView) == -1) {
                return;
            }

            parentVisibleRect.left = 0;
            parentVisibleRect.top = 0;
            parentVisibleRect.right = parentView.getWidth();
            parentVisibleRect.bottom = parentView.getHeight();

            rootContainer.offsetDescendantRectToMyCoords(parentView, parentVisibleRect);

            if (parentVisibleRect.top < 0 || parentVisibleRect.bottom > rootContainer.getHeight()) {

                rect.left = parentView.getLeft();
                rect.top = parentView.getTop();
                rect.right = parentView.getRight();
                rect.bottom = parentView.getBottom();

                parentView.requestRectangleOnScreen(rect, true);
            }
        }
    };

    animation.setDuration(ANIMATION_DURATION);
    view.startAnimation(animation);
}

From source file:com.androcast.illusion.illusionmod.fragments.BaseFragment.java

public void onViewCreated(View view, Bundle saved) {
    super.onViewCreated(view, saved);
    final ViewTreeObserver observer = view.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        public void onGlobalLayout() {
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
                    observer.removeOnGlobalLayoutListener(this);
                else
                    observer.removeGlobalOnLayoutListener(this);

                onViewCreated();//  w w w  .  j  a  va2  s  .  c o  m
            } catch (Exception ignored) {
            }
        }
    });
}

From source file:com.desno365.mods.Tabs.FragmentTab2.java

@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragmenttab2, container, false); // xml tab

    TextView textVersion = (TextView) rootView.findViewById(R.id.latest_version_portal_is); // id TextView version
    textVersion.setText(MainActivity.modsContainer.portal.getVersion()); // MainActivity variable that holds the latest version

    TextView textCompatibility = (TextView) rootView.findViewById(R.id.portal_compatibility); // id TextView compatibility
    textCompatibility.setText(MainActivity.modsContainer.portal.getCompatibility()); // MainActivity variable that holds the versions compatibility

    final TextView textChangelog = (TextView) rootView.findViewById(R.id.portal_changelog); // id TextView changelog
    textChangelog.setText(android.text.Html.fromHtml(MainActivity.modsContainer.portal.getChangelog())); // MainActivity variable that holds the latest changelog
    textChangelog.setMovementMethod(android.text.method.LinkMovementMethod.getInstance());
    textChangelog.setMaxLines(SharedConstants.CHANGELOG_TEXT_MAX_LINES);

    final TextView textShowHide = (TextView) rootView.findViewById(R.id.changelog_show_hide_tab2); // id TextView show/hide changelog
    textShowHide.setText(getResources().getString(R.string.show_changelog));
    textShowHide.setOnClickListener(new View.OnClickListener() {
        @Override//  w  w w . jav a 2  s. c  o m
        public void onClick(View v) {

            if (!displayingAllChangelog) {

                // get the TextView height that will be used when hiding the changelog
                changelogHiddenHeight = textChangelog.getHeight();

                DesnoUtils.expandTextView(container, textChangelog);

                displayingAllChangelog = true;
                textShowHide.setText(getResources().getString(R.string.hide_changelog));

            } else {

                DesnoUtils.collapseTextView(container, textChangelog, changelogHiddenHeight);

                displayingAllChangelog = false;
                textShowHide.setText(getResources().getString(R.string.show_changelog));
            }
        }
    });

    // make the show/hide button invisible if it is not necessary
    ViewTreeObserver vto = textShowHide.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new android.view.ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (textChangelog.getLineCount() <= SharedConstants.CHANGELOG_TEXT_MAX_LINES) {
                textShowHide.setVisibility(View.GONE);
            } else {
                textShowHide.setVisibility(View.VISIBLE);
            }
        }
    });

    return rootView;
}

From source file:com.desno365.mods.Tabs.FragmentTab3.java

@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragmenttab3, container, false); // xml tab

    TextView textVersion = (TextView) rootView.findViewById(R.id.latest_version_laser_is); // id TextView version
    textVersion.setText(MainActivity.modsContainer.laser.getVersion()); // MainActivity variable that holds the latest version

    TextView textCompatibility = (TextView) rootView.findViewById(R.id.laser_compatibility); // id TextView compatibility
    textCompatibility.setText(MainActivity.modsContainer.laser.getCompatibility()); // MainActivity variable that holds the versions compatibility

    final TextView textChangelog = (TextView) rootView.findViewById(R.id.laser_changelog); // id TextView changelog
    textChangelog.setText(android.text.Html.fromHtml(MainActivity.modsContainer.laser.getChangelog())); // MainActivity variable that holds the latest changelog
    textChangelog.setMovementMethod(android.text.method.LinkMovementMethod.getInstance());
    textChangelog.setMaxLines(SharedConstants.CHANGELOG_TEXT_MAX_LINES);

    final TextView textShowHide = (TextView) rootView.findViewById(R.id.changelog_show_hide_tab3); // id TextView show/hide changelog
    textShowHide.setText(getResources().getString(R.string.show_changelog));
    textShowHide.setOnClickListener(new View.OnClickListener() {
        @Override/*from ww  w .  j a  v  a2 s.  c o  m*/
        public void onClick(View v) {

            if (!displayingAllChangelog) {

                // get the TextView height that will be used when hiding the changelog
                changelogHiddenHeight = textChangelog.getHeight();

                DesnoUtils.expandTextView(container, textChangelog);

                displayingAllChangelog = true;
                textShowHide.setText(getResources().getString(R.string.hide_changelog));

            } else {

                DesnoUtils.collapseTextView(container, textChangelog, changelogHiddenHeight);

                displayingAllChangelog = false;
                textShowHide.setText(getResources().getString(R.string.show_changelog));
            }
        }
    });

    // make the show/hide button invisible if it is not necessary
    ViewTreeObserver vto = textShowHide.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new android.view.ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (textChangelog.getLineCount() <= SharedConstants.CHANGELOG_TEXT_MAX_LINES) {
                textShowHide.setVisibility(View.GONE);
            } else {
                textShowHide.setVisibility(View.VISIBLE);
            }
        }
    });

    return rootView;
}