下面列出了怎么用android.text.SpannableString的API类实例代码及写法,或者点击链接到github查看源代码。
@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;
}
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());
}
/** 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);
}
/**
* 替换表情
*
* @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;
}
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;
}
@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);
}
}
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);
}
}
}
}
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));
}
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));
}
}
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;
}
@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 + " ";
}
}
}
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;
}
@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);
}
}
/**
* 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);
}
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);
}
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;
}
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);
}
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;
}
/**
* 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();
}
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;
}
/**
* 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;
}
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();
}
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;
}
}
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;
}
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);
}
@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);
}
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);
}
}
}
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;
}
@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;
}
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);
}
}