android.text.Layout Java Examples

The following examples show how to use android.text.Layout. 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: TextStateDisplay.java    From empty-state-recyclerview with MIT License 6 votes vote down vote up
private void configureTextLayouts(final int availableWidth) {
    if (!textLayoutsConfigured) {
        final int totalNeededPadding = getPaddingLeft() + getPaddingRight();

        // Create new static layout only if needed!
        if ((titleLayout.getWidth() + totalNeededPadding) > availableWidth) {
            this.titleLayout = new StaticLayout(title,
                    titlePaint,
                    availableWidth - totalNeededPadding,
                    Layout.Alignment.ALIGN_NORMAL,
                    1.15f, 0, false);
        }

        // Create new static layout only if needed!
        if ((subtitleLayout.getWidth() + totalNeededPadding) > availableWidth) {
            this.subtitleLayout = new StaticLayout(subtitle,
                    subtitlePaint,
                    availableWidth - totalNeededPadding,
                    Layout.Alignment.ALIGN_NORMAL,
                    1.15f, 0, false);
        }

        textLayoutsConfigured = true;
    }
}
 
Example #2
Source File: CountDownView.java    From CountDownView with MIT License 6 votes vote down vote up
Layout createTextLayout(String text) {
    int textWidth = (int) textPaint.measureText(text);
    int unitTextSize = (int) (textPaint.getTextSize() / 2);
    spannableString.clear();
    spannableString.clearSpans();
    spannableString.append(text);
    if (textAppearanceSpan != null) {
        spannableString.setSpan(textAppearanceSpan, 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    int hrIndex = text.indexOf("h");
    int minIndex = text.indexOf("m");
    int secIndex = text.indexOf("s");
    spannableString.setSpan(new AbsoluteSizeSpan(unitTextSize), hrIndex, hrIndex + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(new AbsoluteSizeSpan(unitTextSize), minIndex, minIndex + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(new AbsoluteSizeSpan(unitTextSize), secIndex, secIndex + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    return new StaticLayout(spannableString, textPaint, textWidth, Layout.Alignment.ALIGN_CENTER, 0, 0, true);
}
 
Example #3
Source File: ColorsText.java    From JsDroidEditor with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * 生成每行文字对应的行号,如果行首为换行符则需要显示行号
 *
 * @return
 */
public Map<Integer, String> getLineNumbers() {
    Map<Integer, String> maps = new HashMap<>();
    Layout layout = getLayout();
    if (layout == null) {
        return maps;
    }
    int lineNumber = 1;
    maps.put(0, Integer.toString(lineNumber));
    int lineCount = getLineCount();
    mMaxLineNumber = 1;
    for (int i = 1; i < lineCount; i++) {
        int charPos = layout.getLineStart(i);
        if (getText().charAt(charPos - 1) == '\n') {
            lineNumber++;
            maps.put(i, Integer.toString(lineNumber));
            mMaxLineNumber = lineNumber;
        }
    }
    return maps;
}
 
Example #4
Source File: ScrollTextView.java    From a with GNU General Public License v3.0 6 votes vote down vote up
private void initOffsetHeight() {
    int paddingTop;
    int paddingBottom;
    int mHeight;
    int mLayoutHeight;

    //获得内容面板
    Layout mLayout = getLayout();
    if (mLayout == null) return;
    //获得内容面板的高度
    mLayoutHeight = mLayout.getHeight();
    //获取上内边距
    paddingTop = getTotalPaddingTop();
    //获取下内边距
    paddingBottom = getTotalPaddingBottom();

    //获得控件的实际高度
    mHeight = getMeasuredHeight();

    //计算滑动距离的边界
    mOffsetHeight = mLayoutHeight + paddingTop + paddingBottom - mHeight;
    if (mOffsetHeight <= 0) {
        scrollTo(0, 0);
    }
}
 
Example #5
Source File: Html.java    From ForPDA with GNU General Public License v3.0 6 votes vote down vote up
private static String getTextDirection(Spanned text, int start, int end) {
    /*final int len = end - start;
    final byte[] levels = ArrayUtils.newUnpaddedByteArray(len);
    final char[] buffer = TextUtils.obtain(len);
    TextUtils.getChars(text, start, end, buffer, 0);
    int paraDir = AndroidBidi.bidi(Layout.DIR_REQUEST_DEFAULT_LTR, buffer, levels, len,
            false *//* no info *//*);*/
    int paraDir = Layout.DIR_LEFT_TO_RIGHT;
    switch (paraDir) {
        case Layout.DIR_RIGHT_TO_LEFT:
            return " dir=\"rtl\"";
        case Layout.DIR_LEFT_TO_RIGHT:
        default:
            return " dir=\"ltr\"";
    }
}
 
Example #6
Source File: CommentTextView.java    From Dashchan with Apache License 2.0 6 votes vote down vote up
private <T> ArrayList<T> findSpansToClick(Layout layout, Spanned spanned, Class<T> type, Point layoutPosition) {
	ArrayList<T> result = new ArrayList<>();
	// Find spans around touch point for better click treatment
	for (int[] deltaAttempt : deltaAttempts) {
		int startX = layoutPosition.x + deltaAttempt[0], startY = layoutPosition.y + deltaAttempt[1];
		T[] spans = findSpansToClickSingle(layout, spanned, type, startX, startY);
		if (spans != null) {
			for (T span : spans) {
				if (span != null) {
					result.add(span);
				}
			}
		}
	}
	return result;
}
 
Example #7
Source File: AlignmentEffect.java    From memoir with Apache License 2.0 6 votes vote down vote up
@Override
public void applyToSelection(RTEditText editor, Selection selectedParagraphs, Layout.Alignment alignment) {
    final Spannable str = editor.getText();

    mSpans2Process.clear();

    for (Paragraph paragraph : editor.getParagraphs()) {
        // find existing AlignmentSpan and add them to mSpans2Process to be removed
        List<RTSpan<Layout.Alignment>> existingSpans = getSpans(str, paragraph, SpanCollectMode.SPAN_FLAGS);
        mSpans2Process.removeSpans(existingSpans, paragraph);

        // if the paragraph is selected then we sure have an alignment
        boolean hasExistingSpans = !existingSpans.isEmpty();
        Alignment newAlignment = paragraph.isSelected(selectedParagraphs) ? alignment :
                                 hasExistingSpans ? existingSpans.get(0).getValue() : null;

        if (newAlignment != null) {
            boolean isRTL = Helper.isRTL(str, paragraph.start(), paragraph.end());
            AlignmentSpan alignmentSpan = new AlignmentSpan(newAlignment, isRTL);
            mSpans2Process.addSpan(alignmentSpan, paragraph);
        }
    }

    // add or remove spans
    mSpans2Process.process(str);
}
 
Example #8
Source File: ViewFinderView.java    From LPR with Apache License 2.0 6 votes vote down vote up
/**
 * 绘制提示文字
 */
private void drawText(Canvas canvas, Rect frame) {
    TextPaint textPaint = new TextPaint();
    textPaint.setAntiAlias(true);
    textPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
    textPaint.setStyle(Paint.Style.FILL);
    textPaint.setColor(scannerOptions.getTipTextColor());
    textPaint.setTextSize(tipTextSize);

    float x = frame.left;//文字开始位置
    //根据 drawTextGravityBottom 文字在扫描框上方还是上文,默认下方
    float y = !scannerOptions.isTipTextToFrameTop() ? frame.bottom + tipTextMargin
            : frame.top - tipTextMargin;

    StaticLayout staticLayout = new StaticLayout(scannerOptions.getTipText(), textPaint, frame.width()
            , Layout.Alignment.ALIGN_CENTER, 1.0f, 0, false);
    canvas.save();
    canvas.translate(x, y);
    staticLayout.draw(canvas);
    canvas.restore();
}
 
Example #9
Source File: TextDrawable.java    From litho with Apache License 2.0 6 votes vote down vote up
public void mount(
    CharSequence text,
    Layout layout,
    float layoutTranslationY,
    ColorStateList colorStateList,
    int userColor,
    int highlightColor,
    ClickableSpan[] clickableSpans) {
  mount(
      text,
      layout,
      0,
      false,
      null,
      userColor,
      highlightColor,
      clickableSpans,
      null,
      null,
      null,
      -1,
      -1,
      0f,
      null);
}
 
Example #10
Source File: BaseMovementMethod.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private int getScrollBoundsRight(TextView widget) {
    final Layout layout = widget.getLayout();
    final int topLine = getTopLine(widget);
    final int bottomLine = getBottomLine(widget);
    if (topLine > bottomLine) {
        return 0;
    }
    int right = Integer.MIN_VALUE;
    for (int line = topLine; line <= bottomLine; line++) {
        final int lineRight = (int) Math.ceil(layout.getLineRight(line));
        if (lineRight > right) {
            right = lineRight;
        }
    }
    return right;
}
 
Example #11
Source File: LyricView.java    From MusicPlayer_XiangDa with GNU General Public License v3.0 6 votes vote down vote up
public void setLyricFile(File file, String charsetName) {
    if (file != null && file.exists()) {
        try {
            setupLyricResource(new FileInputStream(file), charsetName);

            for (int i = 0; i < mLyricInfo.songLines.size(); i++) {

                StaticLayout staticLayout = new StaticLayout(mLyricInfo.songLines.get(i).content, mTextPaint,
                        (int) getRawSize(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_MAX_LENGTH),
                        Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);

                if (staticLayout.getLineCount() > 1) {
                    mEnableLineFeed = true;
                    mExtraHeight = mExtraHeight + (staticLayout.getLineCount() - 1) * mTextHeight;
                }

                mLineFeedRecord.add(i, mExtraHeight);

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    } else {
        invalidateView();
    }
}
 
Example #12
Source File: ListItemSpan.java    From SDHtmlTextView with Apache License 2.0 6 votes vote down vote up
public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top,
                              int baseline, int bottom, CharSequence text, int start, int end,
                              boolean first, Layout l) {
    if (((Spanned) text).getSpanStart(this) == start) {
        Paint.Style style = p.getStyle();

        p.setStyle(Paint.Style.FILL);

        if (mNumber != -1) {
            c.drawText(mNumber + ".", x + dir, baseline, p);
        } else {
            c.drawText("\u2022", x + dir, baseline, p);
        }

        p.setStyle(style);
    }
}
 
Example #13
Source File: StepView.java    From StepView with Apache License 2.0 6 votes vote down vote up
private int measureStepsHeight() {
    textLayouts = new StaticLayout[steps.size()];
    textPaint.setTextSize(textSize);
    int max = 0;
    for (int i = 0; i < steps.size(); i++) {
        String text = steps.get(i);
        Layout.Alignment alignment =
                isRtl() ? Layout.Alignment.ALIGN_OPPOSITE : Layout.Alignment.ALIGN_NORMAL;
        textLayouts[i] = new StaticLayout(
                text,
                textPaint,
                getMeasuredWidth() / steps.size(),
                alignment,
                1,
                0,
                true
        );
        int height = textLayouts[i].getHeight();
        max = Math.max(height, max);
    }
    return max;
}
 
Example #14
Source File: Slidr.java    From android-slidr with Apache License 2.0 6 votes vote down vote up
private void drawIndicatorsTextAbove(Canvas canvas, String text, TextPaint paintText, float x, float y, Layout.Alignment alignment) {

        final float textHeight = calculateTextMultilineHeight(text, paintText);
        y -= textHeight;

        final int width = (int) paintText.measureText(text);
        if (x >= getWidth() - settings.paddingCorners) {
            x = (getWidth() - width - settings.paddingCorners / 2f);
        } else if (x <= 0) {
            x = width / 2f;
        } else {
            x = (x - width / 2f);
        }

        if (x < 0) {
            x = 0;
        }

        if (x + width > getWidth()) {
            x = getWidth() - width;
        }

        drawText(canvas, text, x, y, paintText, alignment);
    }
 
Example #15
Source File: Toolbar.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/** @hide */
public boolean isTitleTruncated() {
    if (mTitleTextView == null) {
        return false;
    }

    final Layout titleLayout = mTitleTextView.getLayout();
    if (titleLayout == null) {
        return false;
    }

    final int lineCount = titleLayout.getLineCount();
    for (int i = 0; i < lineCount; i++) {
        if (titleLayout.getEllipsisCount(i) > 0) {
            return true;
        }
    }
    return false;
}
 
Example #16
Source File: QuoteSpan.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public void drawLeadingMargin(@NonNull Canvas c, @NonNull Paint p, int x, int dir,
        int top, int baseline, int bottom,
        @NonNull CharSequence text, int start, int end,
        boolean first, @NonNull Layout layout) {
    Paint.Style style = p.getStyle();
    int color = p.getColor();

    p.setStyle(Paint.Style.FILL);
    p.setColor(mColor);

    c.drawRect(x, top, x + dir * mStripeWidth, bottom, p);

    p.setStyle(style);
    p.setColor(color);
}
 
Example #17
Source File: AutoResizeTextView.java    From watchlist with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the text size of a clone of the view's {@link TextPaint} object
 * and uses a {@link StaticLayout} instance to measure the height of the text.
 *
 * @param source
 * @param availableWidthPixels
 * @param textSizePixels
 * @return the height of the text when placed in a view
 * with the specified width
 * and when the text has the specified size.
 */
private int getTextHeightPixels(
        CharSequence source,
        int availableWidthPixels,
        float textSizePixels) {
    // Make a copy of the original TextPaint object
    // since the object gets modified while measuring
    // (see also the docs for TextView.getPaint()
    // which states to access it read-only)
    TextPaint textPaintCopy = new TextPaint(getPaint());
    textPaintCopy.setTextSize(textSizePixels);

    // Measure using a StaticLayout instance
    StaticLayout staticLayout = new StaticLayout(
            source,
            textPaintCopy,
            availableWidthPixels,
            Layout.Alignment.ALIGN_NORMAL,
            mLineSpacingMultiplier,
            mLineSpacingExtra,
            true);

    return staticLayout.getHeight();
}
 
Example #18
Source File: AutoSplitTextHelper.java    From ViewPrinter with Apache License 2.0 6 votes vote down vote up
private int computeReleaseOffset(int space) {
    // This is simpler than it looks: we must pass whole lines.
    String logPrefix = logPrefix();
    Layout layout = mView.getLayout();
    int count = layout.getLineCount();
    int removed = 0;
    LOG.v(logPrefix, "computeReleaseOffset:", "space:", space, "lineCount:", count);
    int removeLine = 0;
    for (int i = count - 1; i >= 0; i--) {
        layout.getLineBounds(i, mTmp);
        removed += mTmp.height();
        if (removed >= space) {
            removeLine = i;
            break;
        }
    }
    // We have to remove line i and all subsequent lines.
    LOG.i(logPrefix, "computeReleaseOffset:", "removing line:", removeLine, "and subsequent.");
    return Math.max(layout.getOffsetForHorizontal(removeLine, 0) - 1, 0);
}
 
Example #19
Source File: ReflowText.java    From android-proguards with Apache License 2.0 6 votes vote down vote up
/**
 * Calculate the right boundary for this run (harder than it sounds). As we're a letter ahead,
 * need to grab either current letter start or the end of the previous line. Also need to
 * consider maxLines case, which inserts ellipses at the overflow point – don't include these.
 */
private int getRunRight(
        Layout unrestrictedLayout, Layout maxLinesLayout, int currentLine, int index,
        int line, boolean withinMax, boolean isMaxEllipsis, boolean isLastChar) {
    int runRight;
    if (line != currentLine || isLastChar) {
        if (isMaxEllipsis) {
            runRight = (int) maxLinesLayout.getPrimaryHorizontal(index);
        } else {
            runRight = (int) unrestrictedLayout.getLineMax(currentLine);
        }
    } else {
        if (withinMax) {
            runRight = (int) maxLinesLayout.getPrimaryHorizontal(index);
        } else {
            runRight = (int) unrestrictedLayout.getPrimaryHorizontal(index);
        }
    }
    return runRight;
}
 
Example #20
Source File: FlowViewVertical.java    From StepView with Apache License 2.0 5 votes vote down vote up
private void drawText(Canvas canvas) {
    for (int i = 0; i < maxStep; i++) {
        setPaintColor(i);
        if (null != times && i < proStep)
            canvas.drawText(times[i], bgPositionX - timePaddingRight, stopY - (i * interval) + timeMoveTop, textPaint);
        if (null != titles) {
            canvas.save();
            canvas.translate(bgPositionX + textPaddingLeft, (stopY - (i * interval) - textMoveTop));
            StaticLayout sl = new StaticLayout(titles[i], textPaint, border, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
            sl.draw(canvas);
            canvas.restore();
        }
    }
}
 
Example #21
Source File: TextSpecTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@Test
public void testMinimallyWideThresholdText() {
  final Layout layout = setupWidthTestTextLayout();

  final int resolvedWidth =
      TextSpec.resolveWidth(
          View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
          layout,
          true /* minimallyWide */,
          FULL_TEXT_WIDTH - MINIMAL_TEXT_WIDTH /* minimallyWideThreshold */);

  assertEquals(resolvedWidth, FULL_TEXT_WIDTH);
}
 
Example #22
Source File: WrapWidthTextView.java    From show-case-card-view with Apache License 2.0 5 votes vote down vote up
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    Layout layout = getLayout();
    if (layout != null) {
        int width = (int) Math.ceil(getMaxLineWidth(layout))
            + getCompoundPaddingLeft() + getCompoundPaddingRight();
        int height = getMeasuredHeight();
        setMeasuredDimension(width, height);
    }
}
 
Example #23
Source File: Utils.java    From NetKnight with Apache License 2.0 5 votes vote down vote up
public static void drawMultilineText(Canvas c, String text,
                                     float x, float y,
                                     TextPaint paint,
                                     FSize constrainedToSize,
                                     PointF anchor, float angleDegrees) {

    StaticLayout textLayout = new StaticLayout(
            text, 0, text.length(),
            paint,
            (int) Math.max(Math.ceil(constrainedToSize.width), 1.f),
            Layout.Alignment.ALIGN_NORMAL, 1.f, 0.f, false);


    drawMultilineText(c, textLayout, x, y, paint, anchor, angleDegrees);
}
 
Example #24
Source File: LocalLinkMovementMethod.java    From html-textview with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
    int action = event.getAction();

    if (action == MotionEvent.ACTION_UP ||
            action == MotionEvent.ACTION_DOWN) {
        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) {
            if (action == MotionEvent.ACTION_UP) {
                link[0].onClick(widget);
            } else if (action == MotionEvent.ACTION_DOWN) {
                Selection.setSelection(buffer,
                        buffer.getSpanStart(link[0]),
                        buffer.getSpanEnd(link[0]));
            }

            return true;
        } else {
            Selection.removeSelection(buffer);
            Touch.onTouchEvent(widget, buffer, event);
            return false;
        }
    }
    return Touch.onTouchEvent(widget, buffer, event);
}
 
Example #25
Source File: CustomQuoteSpan.java    From Android-WYSIWYG-Editor with Apache License 2.0 5 votes vote down vote up
@Override
public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom,
                              CharSequence text, int start, int end, boolean first, Layout layout) {
    Paint.Style style = p.getStyle();
    int paintColor = p.getColor();
    p.setStyle(Paint.Style.FILL);
    p.setColor(stripeColor);
    c.drawRect(x, top, x + dir * stripeWidth, bottom, p);
    p.setStyle(style);
    p.setColor(paintColor);
}
 
Example #26
Source File: JustifiedEditText.java    From justified with Apache License 2.0 5 votes vote down vote up
@Override
protected void onTextChanged(final CharSequence text,
                             final int start, final int lengthBefore, final int lengthAfter) {
  super.onTextChanged(text, start, lengthBefore, lengthAfter);
  final Layout layout = getLayout();
  if (layout != null) {
    Justify.setupScaleSpans(this, mSpanStarts, mSpanEnds, mSpans);
  }
}
 
Example #27
Source File: LineUtils.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the lineInfo from the index of the letter in the text
 */
public static int getLineFromIndex(int index, int lineCount, Layout layout) {
    int line;
    int currentIndex = 0;

    for (line = 0; line < lineCount; line++) {
        currentIndex += layout.getLineEnd(line) - layout.getLineStart(line);
        if (currentIndex > index) {
            break;
        }
    }
    return line;
}
 
Example #28
Source File: WebPlayerView.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
public void setDuration(int value) {
    if (duration == value || value < 0 || isStream) {
        return;
    }
    duration = value;
    durationLayout = new StaticLayout(String.format(Locale.US, "%d:%02d", duration / 60, duration % 60), textPaint, AndroidUtilities.dp(1000), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
    if (durationLayout.getLineCount() > 0) {
        durationWidth = (int) Math.ceil(durationLayout.getLineWidth(0));
    }
    invalidate();
}
 
Example #29
Source File: WheelView.java    From zidoorecorder with Apache License 2.0 5 votes vote down vote up
/**
 * Calculates desired height for layout
 * 
 * @param layout
 *            the source layout
 * @return the desired layout height
 */
private int getDesiredHeight(Layout layout) {
	if (layout == null) {
		return 0;
	}
       //调节下面2行垂直居中
	int desired = getItemHeight() * visibleItems - ITEM_OFFSET+16
			- ADDITIONAL_ITEM_HEIGHT;

	// Check against our minimum height
	desired = Math.max(desired, getSuggestedMinimumHeight());

	return desired;
}
 
Example #30
Source File: PromptUtilsUnitTest.java    From MaterialTapTargetPrompt with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsRtlFirstCharacterNotRtlPreJellyBeanMR1()
{
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.JELLY_BEAN);
    final Layout layout = mock(Layout.class);
    when(layout.isRtlCharAt(0)).thenReturn(false);
    when(layout.getAlignment()).thenReturn(Layout.Alignment.ALIGN_NORMAL);
    assertFalse(PromptUtils.isRtlText(layout, null));
}