Example usage for android.widget TextView getLayout

List of usage examples for android.widget TextView getLayout

Introduction

In this page you can find the example usage for android.widget TextView getLayout.

Prototype

public final Layout getLayout() 

Source Link

Document

Gets the android.text.Layout that is currently being used to display the text.

Usage

From source file:im.zico.fancy.common.widget.HackyMovementMethod.java

@Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
    if (mGray == null) {
        mGray = new BackgroundColorSpan(
                ContextCompat.getColor(widget.getContext(), R.color.alpha_spannable_pressed));
    }//from   w w w.java2s .  c o  m

    mIsLinkHit = false;

    int action = event.getAction();

    if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) {
        int x = (int) event.getX();
        int y = (int) event.getY();
        x -= widget.getTotalPaddingLeft();
        y -= widget.getTotalPaddingTop();
        x += widget.getScrollX();
        y += widget.getScrollY();

        int line = widget.getLayout().getLineForVertical(y);
        int offset = widget.getLayout().getOffsetForHorizontal(line, x);

        ClickableSpan[] spans = buffer.getSpans(offset, offset, ClickableSpan.class);

        if (spans.length != 0) {
            int start = buffer.getSpanStart(spans[0]);
            int end = buffer.getSpanEnd(spans[0]);
            mIsLinkHit = true;
            if (action == MotionEvent.ACTION_DOWN) {
                buffer.setSpan(mGray, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else if (action == MotionEvent.ACTION_UP) {
                spans[0].onClick(widget);
                buffer.removeSpan(mGray);
            }
            return true;
        }
    } else {
        buffer.removeSpan(mGray);
    }

    return Touch.onTouchEvent(widget, buffer, event);
}

From source file:com.juick.android.MessageMenu.java

public int getOffsetForPosition(TextView textView, float x, float y) {
    if (textView.getLayout() == null) {
        return -1;
    }/*from ww  w .j  a v a2s.c o m*/
    final int line = getLineAtCoordinate(textView, y);
    final int offset = getOffsetAtCoordinate(textView, line, x);
    return offset;
}

From source file:com.juick.android.MessageMenu.java

private int getOffsetAtCoordinate(TextView textView2, int line, float x) {
    x = convertToLocalHorizontalCoordinate(textView2, x);
    return textView2.getLayout().getOffsetForHorizontal(line, x);
}

From source file:com.juick.android.MessageMenu.java

private int getLineAtCoordinate(TextView textView2, float y) {
    y -= textView2.getTotalPaddingTop();
    // Clamp the position to inside of the view.
    y = Math.max(0.0f, y);/*from w  ww.  j a  v a2s  .  com*/
    y = Math.min(textView2.getHeight() - textView2.getTotalPaddingBottom() - 1, y);
    y += textView2.getScrollY();
    return textView2.getLayout().getLineForVertical((int) y);
}

From source file:Main.java

/**
 * Make a textview to a collapsible textview with the indicator on the right of the textview
 * //from  ww w .  java 2s. 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:org.chromium.chrome.browser.toolbar.ToolbarPhone.java

private Property<TextView, Integer> buildUrlScrollProperty(final View containerView,
        final boolean isContainerRtl) {
    // If the RTL-ness of the container view changes during an animation, the scroll values
    // become invalid.  If that happens, snap to the ending position and no longer update.
    return new Property<TextView, Integer>(Integer.class, "scrollX") {
        private boolean mRtlStateInvalid;

        @Override/*from ww w  .  j ava2s .c o  m*/
        public Integer get(TextView view) {
            return view.getScrollX();
        }

        @Override
        public void set(TextView view, Integer scrollX) {
            if (mRtlStateInvalid)
                return;
            boolean rtl = ApiCompatibilityUtils.isLayoutRtl(containerView);
            if (rtl != isContainerRtl) {
                mRtlStateInvalid = true;
                if (!rtl || mUrlBar.getLayout() != null) {
                    scrollX = 0;
                    if (rtl) {
                        scrollX = (int) view.getLayout().getPrimaryHorizontal(0);
                        scrollX -= view.getWidth();
                    }
                }
            }
            view.setScrollX(scrollX);
        }
    };
}

From source file:org.openintents.notepad.NoteEditor.java

@Override
protected void onResume() {
    super.onResume();
    if (DEBUG) {/*www . jav a 2 s  . co  m*/
        Log.d(TAG, "onResume");
    }

    if (DEBUG) {
        Log.d(TAG, "mDecrypted: " + mDecryptedText);
    }

    // Set auto-link on or off, based on the current setting.
    int autoLink = PreferenceActivity.getAutoLinkFromPreference(this);

    mText.setAutoLinkMask(autoLink);

    mEncrypted = 0;

    if (mState == STATE_EDIT || (mState == STATE_INSERT) || mState == STATE_EDIT_EXTERNAL_NOTE) {
        getNoteFromContentProvider();
    } else if (mState == STATE_EDIT_NOTE_FROM_SDCARD) {
        getNoteFromFile();
    }

    if (mEncrypted == 0 || mDecryptedText != null) {
        applyInsertText();
    }

    // Make sure that we don't use the link movement method.
    // Instead, we need a blend between the arrow key movement (for regular
    // navigation) and
    // the link movement (so the user can click on links).
    mText.setMovementMethod(new ArrowKeyMovementMethod() {
        public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
            // This block is copied and pasted from LinkMovementMethod's
            // onTouchEvent (without the part that actually changes the
            // selection).
            int action = event.getAction();

            if (action == MotionEvent.ACTION_UP) {
                int x = (int) event.getX();
                int y = (int) event.getY();

                x -= widget.getTotalPaddingLeft();
                y -= widget.getTotalPaddingTop();

                x += widget.getScrollX();
                y += widget.getScrollY();

                Layout layout = widget.getLayout();
                int line = layout.getLineForVertical(y);
                int off = layout.getOffsetForHorizontal(line, x);

                ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);

                if (link.length != 0) {
                    link[0].onClick(widget);
                    return true;
                }
            }

            return super.onTouchEvent(widget, buffer, event);
        }
    });

    setTheme(loadTheme());

    startupSearch();
}

From source file:com.android.app.MediaPlaybackActivity.java

public boolean onTouch(View v, MotionEvent event) {
    int action = event.getAction();
    TextView tv = textViewForContainer(v);
    if (tv == null) {
        return false;
    }//from w w w. j  a va 2  s  .c  o  m
    if (action == MotionEvent.ACTION_DOWN) {
        v.setBackgroundColor(0xff606060);
        mInitialX = mLastX = (int) event.getX();
        mDraggingLabel = false;
    } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
        v.setBackgroundColor(0);
        if (mDraggingLabel) {
            Message msg = mLabelScroller.obtainMessage(0, tv);
            mLabelScroller.sendMessageDelayed(msg, 1000);
        }
    } else if (action == MotionEvent.ACTION_MOVE) {
        if (mDraggingLabel) {
            int scrollx = tv.getScrollX();
            int x = (int) event.getX();
            int delta = mLastX - x;
            if (delta != 0) {
                mLastX = x;
                scrollx += delta;
                if (scrollx > mTextWidth) {
                    // scrolled the text completely off the view to the left
                    scrollx -= mTextWidth;
                    scrollx -= mViewWidth;
                }
                if (scrollx < -mViewWidth) {
                    // scrolled the text completely off the view to the right
                    scrollx += mViewWidth;
                    scrollx += mTextWidth;
                }
                tv.scrollTo(scrollx, 0);
            }
            return true;
        }
        int delta = mInitialX - (int) event.getX();
        if (Math.abs(delta) > mTouchSlop) {
            // start moving
            mLabelScroller.removeMessages(0, tv);

            // Only turn ellipsizing off when it's not already off, because it
            // causes the scroll position to be reset to 0.
            if (tv.getEllipsize() != null) {
                tv.setEllipsize(null);
            }
            Layout ll = tv.getLayout();
            // layout might be null if the text just changed, or ellipsizing
            // was just turned off
            if (ll == null) {
                return false;
            }
            // get the non-ellipsized line width, to determine whether scrolling
            // should even be allowed
            mTextWidth = (int) tv.getLayout().getLineWidth(0);
            mViewWidth = tv.getWidth();
            if (mViewWidth > mTextWidth) {
                tv.setEllipsize(TruncateAt.END);
                v.cancelLongPress();
                return false;
            }
            mDraggingLabel = true;
            tv.setHorizontalFadingEdgeEnabled(true);
            v.cancelLongPress();
            return true;
        }
    }
    return false;
}

From source file:com.nttec.everychan.ui.presentation.BoardFragment.java

private Point getSpanCoordinates(View widget, ClickableURLSpan span) {
    TextView parentTextView = (TextView) widget;

    Rect parentTextViewRect = new Rect();

    // Initialize values for the computing of clickedText position
    SpannableString completeText = (SpannableString) (parentTextView).getText();
    Layout textViewLayout = parentTextView.getLayout();

    int startOffsetOfClickedText = completeText.getSpanStart(span);
    int endOffsetOfClickedText = completeText.getSpanEnd(span);
    double startXCoordinatesOfClickedText = textViewLayout.getPrimaryHorizontal(startOffsetOfClickedText);
    double endXCoordinatesOfClickedText = textViewLayout.getPrimaryHorizontal(endOffsetOfClickedText);

    // Get the rectangle of the clicked text
    int currentLineStartOffset = textViewLayout.getLineForOffset(startOffsetOfClickedText);
    int currentLineEndOffset = textViewLayout.getLineForOffset(endOffsetOfClickedText);
    boolean keywordIsInMultiLine = currentLineStartOffset != currentLineEndOffset;
    textViewLayout.getLineBounds(currentLineStartOffset, parentTextViewRect);

    // Update the rectangle position to his real position on screen
    int[] parentTextViewLocation = { 0, 0 };
    parentTextView.getLocationOnScreen(parentTextViewLocation);

    double parentTextViewTopAndBottomOffset = (parentTextViewLocation[1] - parentTextView.getScrollY()
            + parentTextView.getCompoundPaddingTop());

    Rect windowRect = new Rect();
    activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(windowRect);
    parentTextViewTopAndBottomOffset -= windowRect.top;

    parentTextViewRect.top += parentTextViewTopAndBottomOffset;
    parentTextViewRect.bottom += parentTextViewTopAndBottomOffset;

    parentTextViewRect.left += (parentTextViewLocation[0] + startXCoordinatesOfClickedText
            + parentTextView.getCompoundPaddingLeft() - parentTextView.getScrollX());
    parentTextViewRect.right = (int) (parentTextViewRect.left + endXCoordinatesOfClickedText
            - startXCoordinatesOfClickedText);

    int x = (parentTextViewRect.left + parentTextViewRect.right) / 2;
    int y = (parentTextViewRect.top + parentTextViewRect.bottom) / 2;
    if (keywordIsInMultiLine) {
        x = parentTextViewRect.left;/*w  w w . j ava  2  s.c  o  m*/
    }

    return new Point(x, y);
}

From source file:org.telegram.ui.ChatActivity.java

private boolean spanClicked(ListView list, View view, int textViewId) {
    final TextView widget = (TextView) view.findViewById(textViewId);
    if (widget == null) {
        return false;
    }/*from w  w w  . j a  v a 2  s .co m*/
    try {
        list.offsetRectIntoDescendantCoords(widget, mLastTouch);
        int x = mLastTouch.right;
        int y = mLastTouch.bottom;

        x -= widget.getTotalPaddingLeft();
        y -= widget.getTotalPaddingTop();
        x += widget.getScrollX();
        y += widget.getScrollY();

        final Layout layout = widget.getLayout();
        if (layout == null) {
            return false;
        }
        final int line = layout.getLineForVertical(y);
        final int off = layout.getOffsetForHorizontal(line, x);

        final float left = layout.getLineLeft(line);
        if (left > x || left + layout.getLineWidth(line) < x) {
            return false;
        }

        final Editable buffer = new SpannableStringBuilder(widget.getText());
        if (buffer == null) {
            return false;
        }
        final ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);

        if (link.length == 0) {
            return false;
        }

        link[0].onClick(widget);
        return true;
    } catch (Exception e) {
        FileLog.e("tmessages", e);
        return false;
    }
}