android.text.SpannedString Java Examples

The following examples show how to use android.text.SpannedString. 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: ViewMatchersTest.java    From android-test with Apache License 2.0 6 votes vote down vote up
@Test
public void withContentDescriptionString() {
  View view = new View(context);
  view.setContentDescription(null);
  assertTrue(withContentDescription(nullValue(String.class)).matches(view));

  String testText = "test text!";
  view.setContentDescription(testText);
  assertTrue(withContentDescription(is(testText)).matches(view));
  assertFalse(withContentDescription(is("blah")).matches(view));
  assertFalse(withContentDescription(is("")).matches(view));

  // Test withContentDescription(String) directly.
  assertTrue(withContentDescription(testText).matches(view));

  view.setContentDescription(null);
  String nullString = null;
  assertTrue(withContentDescription(nullString).matches(view));
  assertFalse(withContentDescription(testText).matches(view));

  // Test when the view's content description is not a String type.
  view.setContentDescription(new SpannedString(testText));
  assertTrue(withContentDescription(testText).matches(view));
  assertFalse(withContentDescription("different text").matches(view));
}
 
Example #2
Source File: TextUtils.java    From edx-app-android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns displayable styled text from the provided HTML string.
 * <br/>
 * Note: Also handles the case when a String has multiple HTML entities that translate to one
 * character e.g. {@literal &amp;#39;} which is essentially an apostrophe that should normally
 * occur as {@literal &#39;}
 *
 * @param html The source string having HTML content.
 * @return Formatted HTML.
 */
@NonNull
public static Spanned formatHtml(@NonNull String html) {
    final String REGEX = "(&#?[a-zA-Z0-9]+;)";
    final Pattern PATTERN = Pattern.compile(REGEX);

    Spanned formattedHtml = new SpannedString(html);
    String previousHtml = null;

    // Break the loop if there isn't an HTML entity in the text or when all the HTML entities
    // have been decoded. Also break the loop in the special case when a String having the
    // same format as an HTML entity is left but it isn't essentially a decodable HTML entity
    // e.g. &#asdfasd;
    while (PATTERN.matcher(html).find() && !html.equals(previousHtml)) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            formattedHtml = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
        } else {
            formattedHtml = Html.fromHtml(html);
        }
        previousHtml = html;
        html = formattedHtml.toString();
    }

    return formattedHtml;
}
 
Example #3
Source File: Utilities.java    From google-authenticator-android with Apache License 2.0 6 votes vote down vote up
private static Spanned removeTrailingNewlines(Spanned text) {
  int trailingNewlineCharacterCount = 0;
  for (int i = text.length() - 1; i >= 0; i--) {
    char c = text.charAt(i);
    if ((c == '\n') || (c == '\r')) {
      trailingNewlineCharacterCount++;
    } else {
      break;
    }
  }
  if (trailingNewlineCharacterCount == 0) {
    return text;
  }

  return new SpannedString(
      text.subSequence(0, text.length() - trailingNewlineCharacterCount));
}
 
Example #4
Source File: Util.java    From UETool with MIT License 6 votes vote down vote up
private static List<Pair<String, Bitmap>> getTextViewImageSpanBitmap(TextView textView) {
    List<Pair<String, Bitmap>> bitmaps = new ArrayList<>();
    try {
        CharSequence text = textView.getText();
        if (text instanceof SpannedString) {
            Field mSpansField = Class.forName("android.text.SpannableStringInternal").getDeclaredField("mSpans");
            mSpansField.setAccessible(true);
            Object[] spans = (Object[]) mSpansField.get(text);
            for (Object span : spans) {
                if (span instanceof ImageSpan) {
                    bitmaps.add(new Pair<>("SpanBitmap", getDrawableBitmap(((ImageSpan) span).getDrawable())));
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return bitmaps;
}
 
Example #5
Source File: ThreadViewFragment.java    From something.apk with MIT License 6 votes vote down vote up
/**
 * Trigger page load of specific thread by redirecting from a postID. Called by thread list or url links.
 * See startRefresh() and ./request/ThreadPageRequest for volley implementation.
 * @param postId Post ID to redirect to. (Required)
 * @param fromUrl True if request was sent by internal URL request. Used to decide if we should push current state into backstack.
 */
public void loadPost(long postId, boolean fromUrl){
    if(fromUrl && isThreadLoaded()){
        threadBackstack.push(saveThreadState(new Bundle()));
    }else{
        threadBackstack.clear();
    }
    this.ignorePageProgress = true;
    this.postId = postId;
    this.threadId = 0;
    this.page = 0;
    this.maxPage = 0;
    this.forumId = 0;
    this.bookmarked = false;
    this.threadTitle = new SpannedString(getString(R.string.thread_view_loading));
    setTitle(threadTitle);
    invalidateOptionsMenu();
    updateNavbar();
    startRefresh();
    threadView.loadUrl("about:blank");
}
 
Example #6
Source File: ThreadViewFragment.java    From something.apk with MIT License 6 votes vote down vote up
/**
 * Trigger page load of specific thread. Called by thread list or url links.
 * See startRefresh() and ./request/ThreadPageRequest for volley implementation.
 * @param threadId Thread ID for requested thread. (Required)
 * @param page Page number to load, Optional, if -1 will go to last post, if 0 will go to newest unread post.
 * @param userId (Optional) UserId for filtering.
 * @param fromUrl True if request was sent by internal URL request. Used to decide if we should push current state into backstack.
 */
public void loadThread(int threadId, int page, int userId, boolean fromUrl) {
    if(fromUrl && isThreadLoaded()){
        threadBackstack.push(saveThreadState(new Bundle()));
    }else{
        threadBackstack.clear();
    }
    this.ignorePageProgress = true;
    this.threadId = threadId;
    this.page = page;
    this.userId = userId;
    this.maxPage = 0;
    this.forumId = 0;
    this.bookmarked = false;
    this.threadTitle = new SpannedString(getString(R.string.thread_view_loading));
    setTitle(threadTitle);
    invalidateOptionsMenu();
    updateNavbar();
    startRefresh();
    threadView.loadUrl("about:blank");
}
 
Example #7
Source File: MarkdownBuilderTest.java    From user-interface-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void textWithQuote() {
    SpannedString result = builder.markdownToSpans("Text\n> Quote");

    assertEquals("Text\nQuote", result.toString());
    Object[] spans = result.getSpans(0, result.length(), Object.class);
    assertEquals(3, spans.length);

    StyleSpan styleSpan = (StyleSpan) spans[0];
    assertEquals(Typeface.ITALIC, styleSpan.getStyle());
    assertEquals(5, result.getSpanStart(styleSpan));
    assertEquals(10, result.getSpanEnd(styleSpan));
    LeadingMarginSpan leadingMarginSpan = (LeadingMarginSpan) spans[1];
    assertEquals(5, result.getSpanStart(leadingMarginSpan));
    assertEquals(10, result.getSpanEnd(leadingMarginSpan));
    RelativeSizeSpan relativeSizeSpan = (RelativeSizeSpan) spans[2];
    assertEquals(5, result.getSpanStart(relativeSizeSpan));
    assertEquals(10, result.getSpanEnd(relativeSizeSpan));
}
 
Example #8
Source File: RecordingCanvas.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public final void drawText(@NonNull CharSequence text, int start, int end, float x, float y,
        @NonNull Paint paint) {
    if ((start | end | (end - start) | (text.length() - end)) < 0) {
        throw new IndexOutOfBoundsException();
    }
    if (text instanceof String || text instanceof SpannedString
            || text instanceof SpannableString) {
        nDrawText(mNativeCanvasWrapper, text.toString(), start, end, x, y,
                paint.mBidiFlags, paint.getNativeInstance());
    } else if (text instanceof GraphicsOperations) {
        ((GraphicsOperations) text).drawText(this, start, end, x, y,
                paint);
    } else {
        char[] buf = TemporaryBuffer.obtain(end - start);
        TextUtils.getChars(text, start, end, buf, 0);
        nDrawText(mNativeCanvasWrapper, buf, 0, end - start, x, y,
                paint.mBidiFlags, paint.getNativeInstance());
        TemporaryBuffer.recycle(buf);
    }
}
 
Example #9
Source File: CustomMatchers.java    From friendspell with Apache License 2.0 6 votes vote down vote up
public static Matcher<View> withColors(final int... colors) {
  return new BoundedMatcher<View, TextView>(TextView.class) {
    @Override public boolean matchesSafely(TextView textView) {
      SpannedString text = (SpannedString) textView.getText();
      ForegroundColorSpan[] spans = text.getSpans(0, text.length(), ForegroundColorSpan.class);
      if (spans.length != colors.length) {
        return false;
      }
      for (int i = 0; i < colors.length; ++i) {
        if (spans[i].getForegroundColor() != colors[i]) {
          return false;
        }
      }
      return true;
    }
    @Override public void describeTo(Description description) {
      description.appendText("has colors:");
      for (int color : colors) {
        description.appendText(" " + getHexColor(color));
      }
    }
  };
}
 
Example #10
Source File: UiUtils.java    From MVVMArms with Apache License 2.0 5 votes vote down vote up
/**
 * 设置hint大小
 *
 * @param size
 * @param v
 * @param res
 */
public static void setViewHintSize(Context context, int size, TextView v, int res) {
    SpannableString ss = new SpannableString(getResources(context).getString(
            res));
    // 新建一个属性对象,设置文字的大小
    AbsoluteSizeSpan ass = new AbsoluteSizeSpan(size, true);
    // 附加属性到文本
    ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    // 设置hint,一定要进行转换,否则属性会消失
    v.setHint(new SpannedString(ss));
}
 
Example #11
Source File: AndroidHtmlToDisplay.java    From DebugRank with Apache License 2.0 5 votes vote down vote up
@Override
public Spanned convertHtmlToDisplayType(String htmlString, String normalString)
{
    if(htmlString == null)
    {
        return new SpannedString(normalString);
    }

    return Html.fromHtml(htmlString);
}
 
Example #12
Source File: EmphasisTextViewTest.java    From EmphasisTextView with Apache License 2.0 5 votes vote down vote up
@Test
public void multipleMatchesCaseInsensitiveTextColorTest() {

    emphasisTextView.setText("pizzazzZ");
    emphasisTextView.setTextToHighlight("z");
    emphasisTextView.setTextHighlightColor(android.R.color.holo_green_light);
    emphasisTextView.setCaseInsensitive(false);
    emphasisTextView.setHighlightMode(HighlightMode.TEXT);
    emphasisTextView.highlight();

    final ForegroundColorSpan[] highlightSpans = ((SpannedString) emphasisTextView.getText()).getSpans(0, emphasisTextView.getText().length(),
            ForegroundColorSpan.class);
    assertThat("There should only be four highlighted areas", highlightSpans.length, equalTo(4));
    assertThat("Text is colored with wrong color.", highlightSpans[0].getForegroundColor(), equalTo(Color.parseColor("#ff99cc00")));
}
 
Example #13
Source File: RTPlainText.java    From memoir with Apache License 2.0 5 votes vote down vote up
@Override
public RTText convertTo(RTFormat destFormat, RTMediaFactory<RTImage, RTAudio, RTVideo> mediaFactory) {
    if (destFormat instanceof RTFormat.Html) {
        return ConverterTextToHtml.convert(this);
    } else if (destFormat instanceof RTFormat.Spanned) {
        return new RTSpanned(new SpannedString(getText()));
    }

    return super.convertTo(destFormat, mediaFactory);
}
 
Example #14
Source File: ArmsUtils.java    From Aurora with Apache License 2.0 5 votes vote down vote up
/**
 * 设置hint大小
 *
 * @param size
 * @param v
 * @param res
 */
public static void setViewHintSize(Context context, int size, TextView v, int res) {
    SpannableString ss = new SpannableString(getResources(context).getString(
            res));
    // 新建一个属性对象,设置文字的大小
    AbsoluteSizeSpan ass = new AbsoluteSizeSpan(size, true);
    // 附加属性到文本  
    ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    // 设置hint  
    v.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
}
 
Example #15
Source File: RTPlainText.java    From memoir with Apache License 2.0 5 votes vote down vote up
@Override
public RTText convertTo(RTFormat destFormat, RTMediaFactory<RTImage, RTAudio, RTVideo> mediaFactory) {
    if (destFormat instanceof RTFormat.Html) {
        return ConverterTextToHtml.convert(this);
    } else if (destFormat instanceof RTFormat.Spanned) {
        return new RTSpanned(new SpannedString(getText()));
    }

    return super.convertTo(destFormat, mediaFactory);
}
 
Example #16
Source File: MarkdownBuilder.java    From user-interface-samples with Apache License 2.0 5 votes vote down vote up
public SpannedString markdownToSpans(@NonNull final String string) {
    TextMarkdown markdown = parser.parse(string);

    // In the SpannableStringBuilder, the text and the markup are mutable.
    SpannableStringBuilder builder = new SpannableStringBuilder();
    for (int i = 0; i < markdown.getElements().size(); i++) {
        buildSpans(markdown.getElements().get(i), builder);
    }
    return new SpannedString(builder);
}
 
Example #17
Source File: MarkdownBuilderTest.java    From user-interface-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void text() {
    SpannedString result = builder.markdownToSpans("Text");

    Object[] spans = result.getSpans(0, result.length(), Object.class);
    assertEquals(0, spans.length);
}
 
Example #18
Source File: RouteAdapterTest.java    From open with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void shouldBoldName() throws Exception {
    View view = (View) routeAdapter.instantiateItem(viewGroup, 0);
    TextView textView = (TextView) view.findViewById(R.id.full_instruction);
    SpannedString spannedString = (SpannedString) textView.getText();
    assertThat(spannedString.getSpans(0, spannedString.length(), StyleSpan.class)).hasSize(1);
}
 
Example #19
Source File: StreamingTextView.java    From adt-leanback-support with Apache License 2.0 5 votes vote down vote up
public void updateRecognizedText(String stableText, String pendingText) {
    if (DEBUG) Log.d(TAG, "updateText(" + stableText + "," + pendingText + ")");

    if (stableText == null) {
        stableText = "";
    }

    SpannableStringBuilder displayText = new SpannableStringBuilder(stableText);

    if (DOTS_FOR_STABLE) {
        addDottySpans(displayText, stableText, 0);
    }

    if (pendingText != null) {
        int pendingTextStart = displayText.length();
        displayText.append(pendingText);
        if (DOTS_FOR_PENDING) {
            addDottySpans(displayText, pendingText, pendingTextStart);
        } else {
            int pendingColor = getResources().getColor(
                    R.color.lb_search_plate_hint_text_color);
            addColorSpan(displayText, pendingColor, pendingText, pendingTextStart);
        }
    }

    // Start streaming in dots from beginning of partials, or current position,
    // whichever is larger
    mStreamPosition = Math.max(stableText.length(), mStreamPosition);

    // Copy the text and spans to a SpannedString, since editable text
    // doesn't redraw in invalidate() when hardware accelerated
    // if the text or spans havent't changed. (probably a framework bug)
    updateText(new SpannedString(displayText));

    if (ANIMATE_DOTS_FOR_PENDING) {
        startStreamAnimation();
    }
}
 
Example #20
Source File: EmphasisTextViewTest.java    From EmphasisTextView with Apache License 2.0 5 votes vote down vote up
@Test
public void highLightPlusSignTest() {

    emphasisTextView.setText("+301111111111");
    emphasisTextView.setTextToHighlight("+");
    emphasisTextView.setTextHighlightColor("#ff3393b4");
    emphasisTextView.highlight();

    final BackgroundColorSpan[] highlightSpans = ((SpannedString) emphasisTextView.getText()).getSpans(0, emphasisTextView.getText().length(),
            BackgroundColorSpan.class);
    assertThat("There should be only one highlighted area.", highlightSpans.length, equalTo(1));
    for (final BackgroundColorSpan backgroundColorSpan : highlightSpans) {
        assertThat("Text is highlighted with wrong color.", backgroundColorSpan.getBackgroundColor(), equalTo(Color.parseColor("#ff3393b4")));
    }
}
 
Example #21
Source File: SpanFormatter.java    From tindroid with Apache License 2.0 5 votes vote down vote up
public static Spanned toSpanned(final TextView container, final Drafty content,
                                 final ClickListener clicker) {
    if (content == null) {
        return new SpannedString("");
    }
    if (content.isPlain()) {
        return new SpannedString(content.toString());
    }
    TreeNode result = content.format(new SpanFormatter(container, clicker));
    return result.toSpanned();
}
 
Example #22
Source File: EmphasisTextViewTest.java    From EmphasisTextView with Apache License 2.0 5 votes vote down vote up
@Test
public void multipleMatchesCaseInsensitiveTest() {

    emphasisTextView.setText("saladSaladSALAD");
    emphasisTextView.setTextToHighlight("SA");
    emphasisTextView.setTextHighlightColor("#ff3393b4");
    emphasisTextView.setCaseInsensitive(true);
    emphasisTextView.highlight();

    final BackgroundColorSpan[] highlightSpans = ((SpannedString) emphasisTextView.getText()).getSpans(0, emphasisTextView.getText().length(),
            BackgroundColorSpan.class);
    assertThat("There should only be three highlighted areas", highlightSpans.length, equalTo(3));
    assertThat("Text is highlighted with wrong color.", highlightSpans[0].getBackgroundColor(), equalTo(Color.parseColor("#ff3393b4")));
}
 
Example #23
Source File: EmphasisTextViewTest.java    From EmphasisTextView with Apache License 2.0 5 votes vote down vote up
@Test
public void multipleMatchesCaseSensitiveTest() {

    emphasisTextView.setText("saladsalad");
    emphasisTextView.setTextToHighlight("sa");
    emphasisTextView.setTextHighlightColor("#ff3393b4");
    emphasisTextView.setCaseInsensitive(true);
    emphasisTextView.highlight();

    final BackgroundColorSpan[] highlightSpans = ((SpannedString) emphasisTextView.getText()).getSpans(0, emphasisTextView.getText().length(),
            BackgroundColorSpan.class);
    assertThat("There should only be two highlighted areas", highlightSpans.length, equalTo(2));
    assertThat("Text is highlighted with wrong color.", highlightSpans[0].getBackgroundColor(), equalTo(Color.parseColor("#ff3393b4")));
}
 
Example #24
Source File: EmphasisTextViewTest.java    From EmphasisTextView with Apache License 2.0 5 votes vote down vote up
@Test
public void singleMatchCaseSensitiveTest() {

    emphasisTextView.setText("saladSALAD");
    emphasisTextView.setTextToHighlight("sa");
    emphasisTextView.setTextHighlightColor("#ff3393b4");
    emphasisTextView.highlight();

    final BackgroundColorSpan[] highlightSpans = ((SpannedString) emphasisTextView.getText()).getSpans(0, emphasisTextView.getText().length(),
            BackgroundColorSpan.class);
    assertThat("There should only be one highlighted area", highlightSpans.length, equalTo(1));
    assertThat("Text is highlighted with wrong color.", highlightSpans[0].getBackgroundColor(), equalTo(Color.parseColor("#ff3393b4")));
}
 
Example #25
Source File: ArmsUtils.java    From MVPArms with Apache License 2.0 5 votes vote down vote up
/**
 * 设置hint大小
 *
 * @param size
 * @param v
 * @param res
 */
public static void setViewHintSize(Context context, int size, TextView v, int res) {
    SpannableString ss = new SpannableString(getResources(context).getString(
            res));
    // 新建一个属性对象,设置文字的大小
    AbsoluteSizeSpan ass = new AbsoluteSizeSpan(size, true);
    // 附加属性到文本  
    ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    // 设置hint  
    v.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
}
 
Example #26
Source File: UiUtils.java    From AndroidBase with Apache License 2.0 5 votes vote down vote up
/**
 * 设置hint大小
 *
 * @param size
 * @param v
 * @param res
 */
public static void setViewHintSize(int size, TextView v, int res) {
    SpannableString ss = new SpannableString(getResources().getString(
            res));
    // 新建一个属性对象,设置文字的大小
    AbsoluteSizeSpan ass = new AbsoluteSizeSpan(size, true);
    // 附加属性到文本  
    ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    // 设置hint  
    v.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
}
 
Example #27
Source File: EmphasisTextViewTest.java    From EmphasisTextView with Apache License 2.0 5 votes vote down vote up
@Test
public void highlightWithResourceColorIdTest() {

    emphasisTextView.setText("saladSALAD");
    emphasisTextView.setTextToHighlight("sa");
    emphasisTextView.setTextHighlightColor(android.R.color.black);
    emphasisTextView.highlight();

    final BackgroundColorSpan[] highlightSpans = ((SpannedString) emphasisTextView.getText()).getSpans(0, emphasisTextView.getText().length(),
            BackgroundColorSpan.class);
    assertThat("There should only be one highlighted area", highlightSpans.length, equalTo(1));
    assertThat("Text is highlighted with wrong color.", highlightSpans[0].getBackgroundColor(),
            equalTo(context.getResources().getColor(android.R.color.black)));
}
 
Example #28
Source File: ExpandTextView.java    From zone-sdk with MIT License 5 votes vote down vote up
/**
 * 得到最多行那个 最后一个字符的位置,与第一个位置 测出宽度 与 扩展字符 相加 如果大于行宽, 就把endPos--,知道小于。
 * 最后 截取字符  0-endPos 然后拼接  扩展字符 去显示即可!
 */
private void setExpand() {
    calExpand = true;
    Layout layout = getLayout();
    int endPos = layout.getLineEnd(maxLine - 1);
    int startPos = layout.getLineStart(maxLine - 1);
    TextPaint pt = getPaint();

    //如果宽度>测量宽度 就继续 --
    while (Layout.getDesiredWidth(getText(), startPos, endPos, pt) + Layout.getDesiredWidth(new SpannedString(EXPAND), pt) > layout.getWidth()
            && --endPos > startPos) {
    }
    SpannableStringBuilder nowSb = new SpannableStringBuilder(getText().subSequence(0, endPos)).append(EXPAND);
    setText(nowSb);
}
 
Example #29
Source File: RTPlainText.java    From Android-RTEditor with Apache License 2.0 5 votes vote down vote up
@Override
public RTText convertTo(RTFormat destFormat, RTMediaFactory<RTImage, RTAudio, RTVideo> mediaFactory) {
    if (destFormat instanceof RTFormat.Html) {
        return ConverterTextToHtml.convert(this);
    } else if (destFormat instanceof RTFormat.Spanned) {
        return new RTSpanned(new SpannedString(getText()));
    }

    return super.convertTo(destFormat, mediaFactory);
}
 
Example #30
Source File: TextUtils.java    From JotaTextEditor with Apache License 2.0 5 votes vote down vote up
public static CharSequence stringOrSpannedString(CharSequence source) {
    if (source == null)
        return null;
    if (source instanceof SpannedString)
        return source;
    if (source instanceof Spanned)
        return new SpannedString(source);

    return source.toString();
}