android.text.SpannableString Java Examples

The following examples show how to use android.text.SpannableString. 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 Project: sqlbrite   Author: square   File: ItemsAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@Override public View getView(int position, View convertView, ViewGroup parent) {
  if (convertView == null) {
    convertView = inflater.inflate(android.R.layout.simple_list_item_multiple_choice, parent, false);
  }

  TodoItem item = getItem(position);
  CheckedTextView textView = (CheckedTextView) convertView;
  textView.setChecked(item.complete());

  CharSequence description = item.description();
  if (item.complete()) {
    SpannableString spannable = new SpannableString(description);
    spannable.setSpan(new StrikethroughSpan(), 0, description.length(), 0);
    description = spannable;
  }

  textView.setText(description);

  return convertView;
}
 
Example #2
Source Project: RefreashTabView   Author: FreeSunny   File: MainActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void initDesc() {
    SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
    stringBuilder.append(getString(R.string.head_title_desc));
    String link = getString(R.string.head_title_desc_link);
    SpannableString span = new SpannableString(link);
    span.setSpan(new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            //
            Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_LONG).show();
        }
    }, 0, link.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    stringBuilder.append(span);
    stringBuilder.append(" ");
    descTextView.setText(stringBuilder);
    //descTextView.setMovementMethod(LinkMovementMethod.getInstance());
    // fix TextView has LinkMovementMethod intercept Scroll event
    descTextView.setOnTouchListener(LinkMovement.getInstance());
}
 
Example #3
Source Project: AIIA-DNN-benchmark   Author: AIIABenchmark   File: ImageClassifierTF.java    License: Apache License 2.0 6 votes vote down vote up
/** Classifies a frame from the preview stream. */
void classifyFrame(Bitmap bitmap, SpannableStringBuilder builder) {
  if (tflite == null) {
    Log.e(TAG, "Image classifier has not been initialized; Skipped.");
    builder.append(new SpannableString("Uninitialized Classifier."));
  }
  convertBitmapToByteBuffer(bitmap);
  // Here's where the magic happens!!!
  long startTime = SystemClock.uptimeMillis();
  runInference();
  long endTime = SystemClock.uptimeMillis();
  Log.d(TAG, "Timecost to run model inference: " + Long.toString(endTime - startTime));

  // Smooth the results across frames.
  applyFilter();

  // Print the results.
  printTopKLabels(builder);
  long duration = endTime - startTime;
  SpannableString span = new SpannableString(duration + " ms");
  span.setSpan(new ForegroundColorSpan(android.graphics.Color.LTGRAY), 0, span.length(), 0);
  builder.append(span);
}
 
Example #4
Source Project: styT   Author: stytooldex   File: HelpsMainAdapter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 替换表情
 *
 * @param str
 * @param context
 * @return
 */
private SpannableString getSpannableString(String str, Context context) {
    SpannableString spannableString = new SpannableString(str);
    String s = "\\[(.+?)\\]";
    Pattern pattern = Pattern.compile(s, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(spannableString);
    while (matcher.find()) {
        String key = matcher.group();
        int id = Expression.getIdAsName(key);
        if (id != 0) {
            Drawable drawable = context.getResources().getDrawable(id);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            ImageSpan imageSpan = new ImageSpan(drawable);
            spannableString.setSpan(imageSpan, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    return spannableString;
}
 
Example #5
Source Project: Telegram   Author: DrKLO   File: VoIPActivity.java    License: GNU General Public License v2.0 6 votes vote down vote up
private CharSequence getFormattedDebugString() {
    String in = VoIPService.getSharedInstance().getDebugString();
    SpannableString ss = new SpannableString(in);

    int offset = 0;
    do {
        int lineEnd = in.indexOf('\n', offset + 1);
        if (lineEnd == -1)
            lineEnd = in.length();
        String line = in.substring(offset, lineEnd);
        if (line.contains("IN_USE")) {
            ss.setSpan(new ForegroundColorSpan(0xFF00FF00), offset, lineEnd, 0);
        } else {
            if (line.contains(": ")) {
                ss.setSpan(new ForegroundColorSpan(0xAAFFFFFF), offset, offset + line.indexOf(':') + 1, 0);
            }
        }
    } while ((offset = in.indexOf('\n', offset + 1)) != -1);

    return ss;
}
 
Example #6
Source Project: lttrs-android   Author: iNPUTmice   File: BindingAdapters.java    License: Apache License 2.0 6 votes vote down vote up
@BindingAdapter("android:text")
public static void setText(final TextView textView, final FullEmail.From from) {
    if (from instanceof FullEmail.NamedFrom) {
        final FullEmail.NamedFrom named = (FullEmail.NamedFrom) from;
        textView.setText(named.getName());
    } else if (from instanceof FullEmail.DraftFrom) {
        final Context context = textView.getContext();
        final SpannableString spannable = new SpannableString(context.getString(R.string.draft));
        spannable.setSpan(
                new ForegroundColorSpan(ContextCompat.getColor(context, R.color.colorPrimary)),
                0,
                spannable.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        );
        textView.setText(spannable);
    }
}
 
Example #7
Source Project: iBeebo   Author: andforce   File: SmileyPicker.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void addEmotions(SpannableString value, Map<String, Integer> smiles) {
    Paint.FontMetrics fontMetrics = mEditText.getPaint().getFontMetrics();
    int size = (int) (fontMetrics.descent - fontMetrics.ascent);


    Matcher localMatcher = EMOTION_URL.matcher(value);
    while (localMatcher.find()) {
        String key = localMatcher.group(0);
        if (smiles.containsKey(key)) {
            int k = localMatcher.start();
            int m = localMatcher.end();
            if (m - k < 8) {
                Drawable drawable = mContext.getResources().getDrawable(smiles.get(key));
                if (drawable != null) {
                    drawable.setBounds(0, 0, size, size);
                }
                ImageSpan localImageSpan = new ImageSpan(drawable);
                value.setSpan(localImageSpan, k, m, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

    }
}
 
Example #8
Source Project: HaoReader   Author: Invinciblelee   File: SourceDebugActivity.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void printDebugLog(String msg) {
    int titleIndex = msg.indexOf("◆[");
    if (titleIndex >= 0) {
        SpannableString spannableString = new SpannableString(msg);
        spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), titleIndex, msg.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (!TextUtils.isEmpty(tvContent.getText())) {
            tvContent.append("\n");
        }
        tvContent.append(spannableString);
    } else {
        if (!TextUtils.isEmpty(tvContent.getText())) {
            tvContent.append("\n");
        }
        tvContent.append(msg);
    }

    scrollView.post(() -> scrollView.fullScroll(ScrollView.FOCUS_DOWN));

}
 
Example #9
Source Project: arcusandroid   Author: arcus-smart-home   File: StringUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static SpannableString getDateStringDayAndTime (Date dateValue) {
    DateFormat timeFormat = new SimpleDateFormat("  h:mm", Locale.US);
    DateFormat ampmFormat = new SimpleDateFormat(" a", Locale.US);
    DateFormat dateFormat = new SimpleDateFormat("EEE", Locale.US);
    DateFormat dateFormatWithTime = new SimpleDateFormat("    h:mm a", Locale.US);

    if (dateValue == null) {
        return new SpannableString(ArcusApplication.getContext().getString(R.string.unknown_time_value));
    }

    // Date is today; just show the time
    else if (StringUtils.isDateToday(dateValue)) {
        return StringUtils.getSuperscriptSpan(ArcusApplication.getContext().getString(R.string.today), dateFormatWithTime.format(dateValue));
    }

    // Date is yesterday; show "YESTERDAY"
    else if (StringUtils.isDateYesterday(dateValue)) {
        return new SpannableString(ArcusApplication.getContext().getString(R.string.yesterday));
    }

    // Date is in the past; show date
    else {
        return StringUtils.getSuperscriptSpan(WordUtils.capitalize(dateFormat.format(dateValue)), dateFormatWithTime.format(dateValue));
    }
}
 
Example #10
Source Project: ChipsLibrary   Author: AndroidDeveloperLB   File: RecipientEditTextView.java    License: Apache License 2.0 6 votes vote down vote up
void createMoreChipPlainText()
{
// Take the first <= CHIP_LIMIT addresses and get to the end of the second one.
final Editable text=getText();
int start=0;
int end=start;
for(int i=0;i<CHIP_LIMIT;i++)
  {
  end=movePastTerminators(mTokenizer.findTokenEnd(text,start));
  start=end; // move to the next token and get its end.
  }
// Now, count total addresses.
start=0;
final int tokenCount=countTokens(text);
final MoreImageSpan moreSpan=createMoreSpan(tokenCount-CHIP_LIMIT);
final SpannableString chipText=new SpannableString(text.subSequence(end,text.length()));
chipText.setSpan(moreSpan,0,chipText.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
text.replace(end,text.length(),chipText);
mMoreChip=moreSpan;
}
 
Example #11
Source Project: socialview   Author: hendraanggrian   File: SocialAutoCompleteTextView.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CharSequence terminateToken(CharSequence text) {
    int i = text.length();

    while (i > 0 && text.charAt(i - 1) == ' ') {
        i--;
    }

    if (i > 0 && chars.contains(text.charAt(i - 1))) {
        return text;
    } else {
        if (text instanceof Spanned) {
            final Spannable sp = new SpannableString(text + " ");
            TextUtils.copySpansFrom((Spanned) text, 0, text.length(), Object.class, sp, 0);
            return sp;
        } else {
            return text + " ";
        }
    }
}
 
Example #12
Source Project: LoveTalkClient   Author: lanixzcj   File: EmotionUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static CharSequence replace(Context ctx, String text) {
	SpannableString spannableString = new SpannableString(text);
	Matcher matcher = pattern.matcher(text);
	while (matcher.find()) {
		String factText = matcher.group();
		String key = factText.substring(1);
		if (emotionTexts.contains(factText)) {
			Bitmap bitmap = getDrawableByName(ctx, key);
			ImageSpan image = new ImageSpan(ctx, bitmap);
			int start = matcher.start();
			int end = matcher.end();
			spannableString.setSpan(image, start, end,
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
	}
	return spannableString;
}
 
Example #13
Source Project: delion   Author: derry   File: SavePasswordInfoBar.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void createContent(InfoBarLayout layout) {
    super.createContent(layout);
    if (mTitleLinkRangeStart != 0 && mTitleLinkRangeEnd != 0) {
        SpannableString title = new SpannableString(mTitle);
        title.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View view) {
                onLinkClicked();
            }
        }, mTitleLinkRangeStart, mTitleLinkRangeEnd, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        layout.setMessage(title);
    }

    if (!TextUtils.isEmpty(mFirstRunExperienceMessage)) {
        InfoBarControlLayout controlLayout = layout.addControlLayout();
        controlLayout.addDescription(mFirstRunExperienceMessage);
    }
}
 
Example #14
Source Project: Trebuchet   Author: talentlo   File: AutoExpandTextView.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Sets the list of sections in the text view.  This will take the first character of each
 * and space it out in the text view using letter spacing
 */
public void setSections(ArrayList<HighlightedText> sections) {
    mPositions = null;
    if (sections == null || sections.size() == 0) {
        setText("");
        return;
    }

    Resources r = getContext().getResources();
    int highlightColor = r.getColor(R.color.app_scrubber_highlight_color);
    int grayColor = r.getColor(R.color.app_scrubber_gray_color);

    SpannableStringBuilder builder = new SpannableStringBuilder();
    for (HighlightedText highlightText : sections) {
        SpannableString spannable = new SpannableString(highlightText.mText.substring(0, 1));
        spannable.setSpan(
                new ForegroundColorSpan(highlightText.mHighlight ? highlightColor : grayColor),
                0, spannable.length(), 0);
        builder.append(spannable);
    }

    setText(builder);
}
 
Example #15
Source Project: talkback   Author: google   File: TalkBackDumpAccessibilityEventActivity.java    License: Apache License 2.0 6 votes vote down vote up
EventDumperSwitchPreference(Context context, int eventType) {
  super(context);
  this.eventType = eventType;
  setOnPreferenceChangeListener(this);

  String title = AccessibilityEvent.eventTypeToString(eventType);
  // Add TtsSpan to the titles to improve readability.
  SpannableString spannableString = new SpannableString(title);
  TtsSpan ttsSpan = new TtsSpan.TextBuilder(title.replaceAll("_", " ")).build();
  spannableString.setSpan(ttsSpan, 0, title.length(), 0 /* no flag */);
  setTitle(spannableString);

  // Set initial value.
  SharedPreferences prefs = SharedPreferencesUtils.getSharedPreferences(getContext());
  int value = prefs.getInt(getContext().getString(R.string.pref_dump_event_mask_key), 0);
  setChecked((value & eventType) != 0);
}
 
Example #16
Source Project: xDrip   Author: NightscoutFoundation   File: DoNothingService.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static SpannableString nanoStatus() {
    SpannableString pingStatus = null;
    if (lastMessageReceived > 0) {
        long pingSince = JoH.msSince(lastMessageReceived);
        if (pingSince > Constants.MINUTE_IN_MS * 30) {
            pingStatus = Span.colorSpan("No follower sync for: " + JoH.niceTimeScalar(pingSince), BAD.color());
        }
    }
    if (Home.get_follower()) {
        updateLastBg();
        final SpannableString remoteStatus = NanoStatus.getRemote();
        if (last_bg != null) {
            if (JoH.msSince(last_bg.timestamp) > Constants.MINUTE_IN_MS * 15) {
                final SpannableString lastBgStatus = Span.colorSpan("Last from master: " + JoH.niceTimeSince(last_bg.timestamp) + " ago", NOTICE.color());
                return Span.join(true, remoteStatus, pingStatus, lastBgStatus);
            }
        } else {
            return Span.join(true, pingStatus, new SpannableString(gs(R.string.no_data_received_from_master_yet)));
        }
    } else {
        return Span.join(true, pingStatus);
    }
    return null;
}
 
Example #17
Source Project: Telegram   Author: DrKLO   File: Cea708Decoder.java    License: GNU General Public License v2.0 5 votes vote down vote up
public SpannableString buildSpannableString() {
  SpannableStringBuilder spannableStringBuilder =
      new SpannableStringBuilder(captionStringBuilder);
  int length = spannableStringBuilder.length();

  if (length > 0) {
    if (italicsStartPosition != C.POSITION_UNSET) {
      spannableStringBuilder.setSpan(new StyleSpan(Typeface.ITALIC), italicsStartPosition,
          length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    if (underlineStartPosition != C.POSITION_UNSET) {
      spannableStringBuilder.setSpan(new UnderlineSpan(), underlineStartPosition,
          length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    if (foregroundColorStartPosition != C.POSITION_UNSET) {
      spannableStringBuilder.setSpan(new ForegroundColorSpan(foregroundColor),
          foregroundColorStartPosition, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    if (backgroundColorStartPosition != C.POSITION_UNSET) {
      spannableStringBuilder.setSpan(new BackgroundColorSpan(backgroundColor),
          backgroundColorStartPosition, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
  }

  return new SpannableString(spannableStringBuilder);
}
 
Example #18
Source Project: 365browser   Author: mogoweb   File: BrowserAccessibilityManager.java    License: Apache License 2.0 5 votes vote down vote up
protected CharSequence computeText(String text, boolean annotateAsLink, String language) {
    if (annotateAsLink) {
        SpannableString spannable = new SpannableString(text);
        spannable.setSpan(new URLSpan(""), 0, spannable.length(), 0);
        return spannable;
    }
    return text;
}
 
Example #19
Source Project: TinyList   Author: GrenderG   File: MainActivity.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Just info about the app :-)
 */
private void showAboutDialog() {
    final SpannableString spannableString = new SpannableString(getString(R.string.about_msg));
    Linkify.addLinks(spannableString, Linkify.ALL);

    new MaterialDialog.Builder(this)
            .positiveText(android.R.string.ok)
            .title(getString(R.string.app_name) + " " + getString(R.string.app_version))
            .content(spannableString)
            .show();
}
 
Example #20
Source Project: mollyim-android   Author: mollyim   File: LongMessageActivity.java    License: GNU General Public License v3.0 5 votes vote down vote up
private SpannableString linkifyMessageBody(SpannableString messageBody) {
  int     linkPattern = Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES | Linkify.PHONE_NUMBERS;
  boolean hasLinks    = Linkify.addLinks(messageBody, linkPattern);

  if (hasLinks) {
    Stream.of(messageBody.getSpans(0, messageBody.length(), URLSpan.class))
          .filterNot(url -> LinkPreviewUtil.isLegalUrl(url.getURL()))
          .forEach(messageBody::removeSpan);
  }
  return messageBody;
}
 
Example #21
Source Project: AndroidChromium   Author: JackyAndroid   File: SyncCustomizationFragment.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Applies a span to the given string to give it an error color.
 */
private static Spannable errorSummary(String string, Context context) {
    SpannableString summary = new SpannableString(string);
    summary.setSpan(new ForegroundColorSpan(
            ApiCompatibilityUtils.getColor(
                    context.getResources(), R.color.input_underline_error_color)),
            0, summary.length(), 0);
    return summary;
}
 
Example #22
Source Project: revolution-irc   Author: MCMrARM   File: MessageFormatSettingsActivity.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void insertChip(int type) {
    EditText editText = mTextFormatBar.getEditText();
    int sStart = editText.getSelectionStart();
    int sEnd = editText.getSelectionEnd();
    SpannableString ss = new SpannableString("\0");
    ss.setSpan(new MessageBuilder.MetaChipSpan(this, type), 0, 1, MessageBuilder.FORMAT_SPAN_FLAGS);
    editText.getText().replace(sStart, sEnd, ss);
    refreshExamples();
}
 
Example #23
Source Project: mollyim-android   Author: mollyim   File: ContactSelectionListAdapter.java    License: GNU General Public License v3.0 5 votes vote down vote up
private CharSequence getSpannedHeaderString(int position) {
  final String headerString = getHeaderString(position);
  if (isPush(position)) {
    SpannableString spannable = new SpannableString(headerString);
    spannable.setSpan(new ForegroundColorSpan(getContext().getResources().getColor(R.color.core_ultramarine)), 0, headerString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    return spannable;
  } else {
    return headerString;
  }
}
 
Example #24
Source Project: CrawlerForReader   Author: smuyyh   File: SearchResultAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public SpannableString changeTxtColor(String content, String splitText, int color) {
    int start = 0, end;
    SpannableString result = new SpannableString(content = (content == null ? "" : content));
    if (TextUtils.isEmpty(splitText)) {
        return result;
    }
    if (!TextUtils.isEmpty(splitText) && (content.length() >= splitText.length())) {
        while ((start = content.indexOf(splitText, start)) >= 0) {
            end = start + splitText.length();
            result.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            start = end;
        }
    }
    return result;
}
 
Example #25
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_numberpad);

    //Buttons
    Button[] numpad = new Button[10];
    numpad[0] = (Button) findViewById(R.id.button_zero);
    numpad[1] = (Button) findViewById(R.id.button_one);
    numpad[2] = (Button) findViewById(R.id.button_two);
    numpad[3] = (Button) findViewById(R.id.button_three);
    numpad[4] = (Button) findViewById(R.id.button_four);
    numpad[5] = (Button) findViewById(R.id.button_five);
    numpad[6] = (Button) findViewById(R.id.button_six);
    numpad[7] = (Button) findViewById(R.id.button_seven);
    numpad[8] = (Button) findViewById(R.id.button_eight);
    numpad[9] = (Button) findViewById(R.id.button_nine);

    SpannableString[] spannables = createSetSpannables();

    for (int i = 0; i < spannables.length; i++) {
        spannables[i].setSpan(new RelativeSizeSpan(1.8f), 0, 2, 0);
        numpad[i].setText(spannables[i]);
    }

    Button deleteButton = (Button) findViewById(R.id.button_delete);
    SpannableString delete = new SpannableString("  \n DEL");
    delete.setSpan(new RelativeSizeSpan(1.8f), 0, 1, 0);
    deleteButton.setTextColor(Color.TRANSPARENT);
    deleteButton.setText(delete);

    Button resetButton = (Button) findViewById(R.id.button_reset);
    SpannableString reset = new SpannableString("  \n RESET");
    reset.setSpan(new RelativeSizeSpan(1.8f), 0, 2, 0);
    resetButton.setTextColor(Color.TRANSPARENT);
    resetButton.setText(reset);

    overridePendingTransition(0, 0);
}
 
Example #26
Source Project: mollyim-android   Author: mollyim   File: MediaMmsMessageRecord.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public SpannableString getDisplayBody(@NonNull Context context) {
  if (MmsDatabase.Types.isFailedDecryptType(type)) {
    return emphasisAdded(context.getString(R.string.MmsMessageRecord_bad_encrypted_mms_message));
  } else if (MmsDatabase.Types.isDuplicateMessageType(type)) {
    return emphasisAdded(context.getString(R.string.SmsMessageRecord_duplicate_message));
  } else if (MmsDatabase.Types.isNoRemoteSessionType(type)) {
    return emphasisAdded(context.getString(R.string.MmsMessageRecord_mms_message_encrypted_for_non_existing_session));
  } else if (isLegacyMessage()) {
    return emphasisAdded(context.getString(R.string.MessageRecord_message_encrypted_with_a_legacy_protocol_version_that_is_no_longer_supported));
  }

  return super.getDisplayBody(context);
}
 
Example #27
Source Project: barcodescanner-lib-aar   Author: EddyVerbruggen   File: SearchBookContentsListItem.java    License: MIT License 5 votes vote down vote up
public void set(SearchBookContentsResult result) {
  pageNumberView.setText(result.getPageNumber());
  String snippet = result.getSnippet();
  if (snippet.isEmpty()) {
    snippetView.setText("");
  } else {
    if (result.getValidSnippet()) {
      String lowerQuery = SearchBookContentsResult.getQuery().toLowerCase(Locale.getDefault());
      String lowerSnippet = snippet.toLowerCase(Locale.getDefault());
      Spannable styledSnippet = new SpannableString(snippet);
      StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
      int queryLength = lowerQuery.length();
      int offset = 0;
      while (true) {
        int pos = lowerSnippet.indexOf(lowerQuery, offset);
        if (pos < 0) {
          break;
        }
        styledSnippet.setSpan(boldSpan, pos, pos + queryLength, 0);
        offset = pos + queryLength;
      }
      snippetView.setText(styledSnippet);
    } else {
      // This may be an error message, so don't try to bold the query terms within it
      snippetView.setText(snippet);
    }
  }
}
 
Example #28
Source Project: AndroidMaterialDesign   Author: chiclaim   File: UserProfileActivity.java    License: Apache License 2.0 5 votes vote down vote up
private static SpannableStringBuilder getSsb(String prefix, String suffix, int prefixColor, int suffixColor) {
    if (TextUtils.isEmpty(prefix)) {
        prefix = "0";
    }
    SpannableStringBuilder ssb = new SpannableStringBuilder();
    SpannableString redSpannable = new SpannableString(prefix + suffix);
    int prefixLen = prefix.length();
    redSpannable.setSpan(new ForegroundColorSpan(prefixColor), 0, prefixLen, 0);
    redSpannable.setSpan(new ForegroundColorSpan(suffixColor), prefixLen, suffix.length() + prefixLen, 0);
    ssb.append(redSpannable);
    return ssb;
}
 
Example #29
Source Project: bither-android   Author: bither   File: OptionColdFragment.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public CharSequence getOptionName(int index) {
    UnitUtilWrapper.BitcoinUnitWrapper unit = UnitUtilWrapper.BitcoinUnitWrapper.values()
            [index];
    SpannableString s = new SpannableString("  " + unit.name());
    Bitmap bmp = UnitUtilWrapper.getBtcSlimSymbol(getResources().getColor(R.color
            .text_field_text_color), getResources().getDisplayMetrics().scaledDensity *
            15.6f, unit);
    s.setSpan(new ImageSpan(getActivity(), bmp, ImageSpan.ALIGN_BASELINE), 0, 1,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    return s;
}
 
Example #30
Source Project: Dashchan   Author: Mishiranu   File: MarkupButtonProvider.java    License: Apache License 2.0 5 votes vote down vote up
public void applyTextAndStyle(Button button) {
	Object span = getSpan(button.getContext());
	if (span != null) {
		SpannableString spannable = new SpannableString(text);
		spannable.setSpan(span, 0, spannable.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
		button.setText(spannable);
	} else {
		button.setText(text);
	}
}