List of usage examples for android.text SpannableStringBuilder setSpan
public void setSpan(Object what, int start, int end, int flags)
From source file:com.silentcircle.contacts.vcard.ManageVCardActivity.java
private Dialog getVCardFileSelectDialog(boolean multipleSelect) { final int size = mAllVCardFileList.size(); final VCardSelectedListener listener = new VCardSelectedListener(multipleSelect); final AlertDialog.Builder builder = new AlertDialog.Builder(this) .setTitle(R.string.select_vcard_title_remove).setPositiveButton(android.R.string.ok, listener) .setOnCancelListener(mCancelListener).setNegativeButton(android.R.string.cancel, mCancelListener); CharSequence[] items = new CharSequence[size]; DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (int i = 0; i < size; i++) { VCardFile vcardFile = mAllVCardFileList.get(i); SpannableStringBuilder stringBuilder = new SpannableStringBuilder(); stringBuilder.append(vcardFile.getName()); stringBuilder.append('\n'); int indexToBeSpanned = stringBuilder.length(); // Smaller date text looks better, since each file name becomes easier to read. // The value set to RelativeSizeSpan is arbitrary. You can change it to any other // value (but the value bigger than 1.0f would not make nice appearance :) stringBuilder.append("(" + dateFormat.format(new Date(vcardFile.getLastModified())) + ")"); stringBuilder.setSpan(new RelativeSizeSpan(0.7f), indexToBeSpanned, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); items[i] = stringBuilder;//from www . j a v a2 s . com } if (multipleSelect) { builder.setMultiChoiceItems(items, (boolean[]) null, listener); } else { builder.setSingleChoiceItems(items, 0, listener); } return builder.create(); }
From source file:com.ruesga.rview.tasks.AsyncTextDiffProcessor.java
private CharSequence processHighlightTabs(CharSequence text) { if (!mHighlightTabs || !text.toString().contains(StringHelper.NON_PRINTABLE_CHAR)) { return text; }/*from w w w . j ava 2 s . c o m*/ int color = ContextCompat.getColor(mContext, R.color.diffHighlightColor); SpannableStringBuilder ssb = new SpannableStringBuilder(text); String line = text.toString(); int index = line.length(); while ((index = line.lastIndexOf(StringHelper.NON_PRINTABLE_CHAR, index)) != -1) { ssb.replace(index, index + 1, "\u00BB "); ssb.setSpan(new ForegroundColorSpan(color), index, index + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); ssb.setSpan(new StyleSpan(Typeface.BOLD), index, index + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); index--; } return ssb; }
From source file:com.sina.weibo.sdk.demo.sample.activity.TestFragment.java
public SpannableStringBuilder setTextColor(String str) { // ????????/*from w w w .jav a2 s .c o m*/ int bstart = 0; int bend = 0; int fstart = 0; int fend = 0; int a = 0; int b = 0; int c = 0; SpannableStringBuilder style = new SpannableStringBuilder(str); while (true) { bstart = str.indexOf("@", bend); a = str.indexOf(" ", bstart); c = str.indexOf(":", bstart); a = a < c ? a : c; if (bstart < 0) { break; } else { if (a < 0) { break; } else { bend = a; } style.setSpan(new ForegroundColorSpan(0xFF0099ff), bstart, a, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); } } while (true) { fstart = str.indexOf("#", fend); b = str.indexOf("#", fstart + 1); if (fstart < 0) { break; } else { if (b < 0) { break; } else { fend = b + 1; } style.setSpan(new ForegroundColorSpan(0xFF0099ff), fstart, fend, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); } } return style; }
From source file:org.kontalk.ui.GroupInfoFragment.java
private void showIdentityDialog(Contact c, boolean subscribed) { final String jid = c.getJID(); final String dialogFingerprint; final String fingerprint; final boolean selfJid = Authenticator.isSelfJID(getContext(), jid); int titleResId = R.string.title_identity; String uid;/* w w w .ja v a 2 s .c o m*/ PGPPublicKeyRing publicKey = Keyring.getPublicKey(getContext(), jid, MyUsers.Keys.TRUST_UNKNOWN); if (publicKey != null) { PGPPublicKey pk = PGP.getMasterKey(publicKey); String rawFingerprint = PGP.getFingerprint(pk); fingerprint = PGP.formatFingerprint(rawFingerprint); uid = PGP.getUserId(pk, XmppStringUtils.parseDomain(jid)); dialogFingerprint = selfJid ? null : rawFingerprint; } else { // FIXME using another string fingerprint = getString(R.string.peer_unknown); uid = null; dialogFingerprint = null; } if (Authenticator.isSelfJID(getContext(), jid)) { titleResId = R.string.title_identity_self; } SpannableStringBuilder text = new SpannableStringBuilder(); if (c.getName() != null && c.getNumber() != null) { text.append(c.getName()).append('\n').append(c.getNumber()); } else { int start = text.length(); text.append(uid != null ? uid : c.getJID()); text.setSpan(SystemUtils.getTypefaceSpan(Typeface.BOLD), start, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } text.append('\n').append(getString(R.string.text_invitation2)).append('\n'); int start = text.length(); text.append(fingerprint); text.setSpan(SystemUtils.getTypefaceSpan(Typeface.BOLD), start, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); int trustStringId; CharacterStyle[] trustSpans; if (subscribed) { int trustedLevel; if (c.isKeyChanged()) { // the key has changed and was not trusted yet trustedLevel = MyUsers.Keys.TRUST_UNKNOWN; } else { trustedLevel = c.getTrustedLevel(); } switch (trustedLevel) { case MyUsers.Keys.TRUST_IGNORED: trustStringId = R.string.trust_ignored; trustSpans = new CharacterStyle[] { SystemUtils.getTypefaceSpan(Typeface.BOLD), SystemUtils.getColoredSpan(getContext(), R.color.button_danger) }; break; case MyUsers.Keys.TRUST_VERIFIED: trustStringId = R.string.trust_verified; trustSpans = new CharacterStyle[] { SystemUtils.getTypefaceSpan(Typeface.BOLD), SystemUtils.getColoredSpan(getContext(), R.color.button_success) }; break; case MyUsers.Keys.TRUST_UNKNOWN: default: trustStringId = R.string.trust_unknown; trustSpans = new CharacterStyle[] { SystemUtils.getTypefaceSpan(Typeface.BOLD), SystemUtils.getColoredSpan(getContext(), R.color.button_danger) }; break; } } else { trustStringId = R.string.status_notsubscribed; trustSpans = new CharacterStyle[] { SystemUtils.getTypefaceSpan(Typeface.BOLD), }; } text.append('\n').append(getString(R.string.status_label)); start = text.length(); text.append(getString(trustStringId)); for (CharacterStyle span : trustSpans) text.setSpan(span, start, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); MaterialDialog.Builder builder = new MaterialDialog.Builder(getContext()).content(text).title(titleResId); if (dialogFingerprint != null && subscribed) { builder.onAny(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { switch (which) { case POSITIVE: // trust the key trustKey(jid, dialogFingerprint, MyUsers.Keys.TRUST_VERIFIED); break; case NEUTRAL: // ignore the key trustKey(jid, dialogFingerprint, MyUsers.Keys.TRUST_IGNORED); break; case NEGATIVE: // untrust the key trustKey(jid, dialogFingerprint, MyUsers.Keys.TRUST_UNKNOWN); break; } } }).positiveText(R.string.button_accept).positiveColorRes(R.color.button_success) .neutralText(R.string.button_ignore).negativeText(R.string.button_refuse) .negativeColorRes(R.color.button_danger); } else if (!selfJid) { builder.onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { openChat(jid); } }).positiveText(R.string.button_private_chat); } builder.show(); }
From source file:org.tlhInganHol.android.klingonassistant.EntryActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TTS:/* w ww . ja va 2 s .co m*/ // Initialize text-to-speech. This is an asynchronous operation. // The OnInitListener (second argument) is called after initialization completes. // Log.d(TAG, "Initialising TTS"); mTts = new TextToSpeech(this, this, // TextToSpeech.OnInitListener "org.tlhInganHol.android.klingonttsengine"); // Requires API 14. setDrawerContentView(R.layout.entry); Resources resources = getResources(); JellyBeanSpanFixTextView entryTitle = (JellyBeanSpanFixTextView) findViewById(R.id.entry_title); JellyBeanSpanFixTextView entryText = (JellyBeanSpanFixTextView) findViewById(R.id.definition); // TODO: Save and restore bundle state to preserve links. Uri uri = getIntent().getData(); // Log.d(TAG, "EntryActivity - uri: " + uri.toString()); // TODO: Disable the "About" menu item if this is the "About" entry. mParentQuery = getIntent().getStringExtra(SearchManager.QUERY); // Retrieve the entry's data. // Note: managedQuery is deprecated since API 11. Cursor cursor = managedQuery(uri, KlingonContentDatabase.ALL_KEYS, null, null, null); KlingonContentProvider.Entry entry = new KlingonContentProvider.Entry(cursor, getBaseContext()); // Handle alternative spellings here. if (entry.isAlternativeSpelling()) { // TODO: Immediate redirect to query in entry.getDefinition(); } // Get the shared preferences. SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); // Set the entry's name (along with info like "slang", formatted in HTML). entryTitle.invalidate(); boolean useKlingonFont = sharedPrefs.getBoolean(Preferences.KEY_KLINGON_FONT_CHECKBOX_PREFERENCE, /* default */false); Typeface klingonTypeface = KlingonAssistant.getKlingonFontTypeface(getBaseContext()); if (useKlingonFont) { // Preference is set to display this in {pIqaD}! entryTitle.setTypeface(klingonTypeface); entryTitle.setText(entry.getEntryNameInKlingonFont()); } else { // Boring transcription based on English (Latin) alphabet. entryTitle.setText(Html.fromHtml(entry.getFormattedEntryName(/* isHtml */true))); } mEntryName = entry.getEntryName(); // Set the colour for the entry name depending on its part of speech. boolean useColours = sharedPrefs.getBoolean(Preferences.KEY_USE_COLOURS_CHECKBOX_PREFERENCE, /* default */true); if (useColours) { entryTitle.setTextColor(entry.getTextColor()); } // Create the expanded definition. String pos = entry.getFormattedPartOfSpeech(/* isHtml */false); String expandedDefinition = pos + entry.getDefinition(); // Show the German definition. String definition_DE = ""; boolean displayGermanEntry = entry.shouldDisplayGerman(); int germanDefinitionStart = -1; String germanDefinitionHeader = "\n" + resources.getString(R.string.label_german) + ": "; if (displayGermanEntry) { germanDefinitionStart = expandedDefinition.length(); definition_DE = entry.getDefinition_DE(); expandedDefinition += germanDefinitionHeader + definition_DE; } // Set the share intent. setShareEntryIntent(entry); // Show the basic notes. String notes = entry.getNotes(); if (!notes.equals("")) { expandedDefinition += "\n\n" + notes; } // If this entry is hypothetical or extended canon, display warnings. if (entry.isHypothetical() || entry.isExtendedCanon()) { expandedDefinition += "\n\n"; if (entry.isHypothetical()) { expandedDefinition += resources.getString(R.string.warning_hypothetical); } if (entry.isExtendedCanon()) { expandedDefinition += resources.getString(R.string.warning_extended_canon); } } // Show synonyms, antonyms, and related entries. String synonyms = entry.getSynonyms(); String antonyms = entry.getAntonyms(); String seeAlso = entry.getSeeAlso(); if (!synonyms.equals("")) { expandedDefinition += "\n\n" + resources.getString(R.string.label_synonyms) + ": " + synonyms; } if (!antonyms.equals("")) { expandedDefinition += "\n\n" + resources.getString(R.string.label_antonyms) + ": " + antonyms; } if (!seeAlso.equals("")) { expandedDefinition += "\n\n" + resources.getString(R.string.label_see_also) + ": " + seeAlso; } // Display components if that field is not empty, unless we are showing an analysis link, in // which case we want to hide the components. boolean showAnalysis = entry.isSentence() || entry.isDerivative(); String components = entry.getComponents(); if (!components.equals("")) { // Treat the components column of inherent plurals and their // singulars differently than for other entries. if (entry.isInherentPlural()) { expandedDefinition += "\n\n" + String.format(resources.getString(R.string.info_inherent_plural), components); } else if (entry.isSingularFormOfInherentPlural()) { expandedDefinition += "\n\n" + String.format(resources.getString(R.string.info_singular_form), components); } else if (!showAnalysis) { // This is just a regular list of components. expandedDefinition += "\n\n" + resources.getString(R.string.label_components) + ": " + components; } } // Display plural information. if (!entry.isPlural() && !entry.isInherentPlural() && !entry.isPlural()) { if (entry.isBeingCapableOfLanguage()) { expandedDefinition += "\n\n" + resources.getString(R.string.info_being); } else if (entry.isBodyPart()) { expandedDefinition += "\n\n" + resources.getString(R.string.info_body); } } // If the entry is a useful phrase, link back to its category. if (entry.isSentence()) { String sentenceType = entry.getSentenceType(); if (!sentenceType.equals("")) { // Put the query as a placeholder for the actual category. expandedDefinition += "\n\n" + resources.getString(R.string.label_category) + ": {" + entry.getSentenceTypeQuery() + "}"; } } // If the entry is a sentence, make a link to analyse its components. if (showAnalysis) { String analysisQuery = entry.getEntryName(); if (!components.equals("")) { // Strip the brackets around each component so they won't be processed. analysisQuery += ":" + entry.getPartOfSpeech(); int homophoneNumber = entry.getHomophoneNumber(); if (homophoneNumber != -1) { analysisQuery += ":" + homophoneNumber; } analysisQuery += KlingonContentProvider.Entry.COMPONENTS_MARKER + components.replaceAll("[{}]", ""); } expandedDefinition += "\n\n" + resources.getString(R.string.label_analyze) + ": {" + analysisQuery + "}"; } // Show the examples. String examples = entry.getExamples(); if (!examples.equals("")) { expandedDefinition += "\n\n" + resources.getString(R.string.label_examples) + ": " + examples; } // Show the source. String source = entry.getSource(); if (!source.equals("")) { expandedDefinition += "\n\n" + resources.getString(R.string.label_sources) + ": " + source; } // If this is a verb (but not a prefix or suffix), show the transitivity information. String transitivity = ""; if (entry.isVerb() && sharedPrefs.getBoolean(Preferences.KEY_SHOW_TRANSITIVITY_CHECKBOX_PREFERENCE, /* default */ true)) { // This is a verb and show transitivity preference is set to true. transitivity = entry.getTransitivityString(); } int transitivityStart = -1; String transitivityHeader = "\n\n" + resources.getString(R.string.label_transitivity) + ": "; boolean showTransitivityInformation = !transitivity.equals(""); if (showTransitivityInformation) { transitivityStart = expandedDefinition.length(); expandedDefinition += transitivityHeader + transitivity; } // Show the hidden notes. String hiddenNotes = ""; if (sharedPrefs.getBoolean(Preferences.KEY_SHOW_ADDITIONAL_INFORMATION_CHECKBOX_PREFERENCE, /* default */ true)) { // Show additional information preference set to true. hiddenNotes = entry.getHiddenNotes(); } int hiddenNotesStart = -1; String hiddenNotesHeader = "\n\n" + resources.getString(R.string.label_additional_information) + ": "; if (!hiddenNotes.equals("")) { hiddenNotesStart = expandedDefinition.length(); expandedDefinition += hiddenNotesHeader + hiddenNotes; } // Format the expanded definition, including linkifying the links to other entries. float smallTextScale = (float) 0.8; SpannableStringBuilder ssb = new SpannableStringBuilder(expandedDefinition); int intermediateFlags = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_INTERMEDIATE; int finalFlags = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE; if (!pos.equals("")) { // Italicise the part of speech. ssb.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, pos.length(), finalFlags); } if (displayGermanEntry) { // Reduce the size of the German definition. ssb.setSpan(new RelativeSizeSpan(smallTextScale), germanDefinitionStart, germanDefinitionStart + germanDefinitionHeader.length() + definition_DE.length(), finalFlags); } if (showTransitivityInformation) { // Reduce the size of the transitivity information. ssb.setSpan(new RelativeSizeSpan(smallTextScale), transitivityStart, transitivityStart + transitivityHeader.length() + transitivity.length(), finalFlags); } if (!hiddenNotes.equals("")) { // Reduce the size of the hidden notes. ssb.setSpan(new RelativeSizeSpan(smallTextScale), hiddenNotesStart, hiddenNotesStart + hiddenNotesHeader.length() + hiddenNotes.length(), finalFlags); } Matcher m = KlingonContentProvider.Entry.ENTRY_PATTERN.matcher(expandedDefinition); while (m.find()) { // Strip the brackets {} to get the query. String query = expandedDefinition.substring(m.start() + 1, m.end() - 1); LookupClickableSpan viewLauncher = new LookupClickableSpan(query); // Process the linked entry information. KlingonContentProvider.Entry linkedEntry = new KlingonContentProvider.Entry(query, getBaseContext()); // Log.d(TAG, "linkedEntry.getEntryName() = " + linkedEntry.getEntryName()); // Delete the brackets and metadata parts of the string (which includes analysis components). ssb.delete(m.start() + 1 + linkedEntry.getEntryName().length(), m.end()); ssb.delete(m.start(), m.start() + 1); int end = m.start() + linkedEntry.getEntryName().length(); // Insert link to the category for a useful phrase. if (entry.isSentence() && !entry.getSentenceType().equals("") && linkedEntry.getEntryName().equals("*")) { // Delete the "*" placeholder. ssb.delete(m.start(), m.start() + 1); // Insert the category name. ssb.insert(m.start(), entry.getSentenceType()); end += entry.getSentenceType().length() - 1; } // Set the font and link. // TODO: Source should link to description of the source. // This is true if this entry doesn't launch an EntryActivity. boolean disableEntryLink = linkedEntry.doNotLink() || linkedEntry.isSource() || linkedEntry.isURL(); // The last span set on a range must have finalFlags. int maybeFinalFlags = disableEntryLink ? finalFlags : intermediateFlags; if (linkedEntry.isSource()) { // Names of sources are in italics. ssb.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), m.start(), end, maybeFinalFlags); } else if (linkedEntry.isURL()) { // Linkify URL if there is one. String url = linkedEntry.getURL(); if (!url.equals("")) { ssb.setSpan(new URLSpan(url), m.start(), end, maybeFinalFlags); } } else if (useKlingonFont) { // Display the text using the Klingon font. Categories (which have an entry of "*") must // be handled specially. String klingonEntryName = !linkedEntry.getEntryName().equals("*") ? linkedEntry.getEntryNameInKlingonFont() : KlingonContentProvider.convertStringToKlingonFont(entry.getSentenceType()); ssb.delete(m.start(), end); ssb.insert(m.start(), klingonEntryName); end = m.start() + klingonEntryName.length(); ssb.setSpan(new KlingonTypefaceSpan("", klingonTypeface), m.start(), end, maybeFinalFlags); } else { // Klingon is in bold serif. ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), m.start(), end, intermediateFlags); ssb.setSpan(new TypefaceSpan("serif"), m.start(), end, maybeFinalFlags); } // If linked entry is hypothetical or extended canon, insert a "?" in front. if (linkedEntry.isHypothetical() || linkedEntry.isExtendedCanon()) { ssb.insert(m.start(), "?"); ssb.setSpan(new RelativeSizeSpan(smallTextScale), m.start(), m.start() + 1, intermediateFlags); ssb.setSpan(new SuperscriptSpan(), m.start(), m.start() + 1, maybeFinalFlags); end++; } // Only apply colours to verbs, nouns, and affixes (exclude BLUE and WHITE). if (!disableEntryLink) { // Link to view launcher. ssb.setSpan(viewLauncher, m.start(), end, useColours ? intermediateFlags : finalFlags); } // Set the colour last, so it's not overridden by other spans. if (useColours) { ssb.setSpan(new ForegroundColorSpan(linkedEntry.getTextColor()), m.start(), end, finalFlags); } String linkedPos = linkedEntry.getBracketedPartOfSpeech(/* isHtml */false); if (!linkedPos.equals("") && linkedPos.length() > 1) { ssb.insert(end, linkedPos); int rightBracketLoc = linkedPos.indexOf(")"); if (rightBracketLoc != -1) { // linkedPos is always of the form " (pos)[ (def'n N)]", we want to italicise // the "pos" part only. ssb.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), end + 2, end + rightBracketLoc, finalFlags); } } // Rinse and repeat. expandedDefinition = ssb.toString(); m = KlingonContentProvider.Entry.ENTRY_PATTERN.matcher(expandedDefinition); } // Display the entry name and definition. entryText.invalidate(); entryText.setText(ssb); entryText.setMovementMethod(LinkMovementMethod.getInstance()); }
From source file:com.android.tv.guide.ProgramItemView.java
public void setValues(TableEntry entry, int selectedGenreId, long fromUtcMillis, long toUtcMillis, String gapTitle) {/*from www.ja va2 s . c om*/ mTableEntry = entry; ViewGroup.LayoutParams layoutParams = getLayoutParams(); layoutParams.width = entry.getWidth(); setLayoutParams(layoutParams); String title = entry.program != null ? entry.program.getTitle() : null; String episode = entry.program != null ? entry.program.getEpisodeDisplayTitle(getContext()) : null; TextAppearanceSpan titleStyle = sGrayedOutProgramTitleStyle; TextAppearanceSpan episodeStyle = sGrayedOutEpisodeTitleStyle; if (entry.getWidth() < sVisibleThreshold) { setText(null); } else { if (entry.isGap()) { title = gapTitle; episode = null; } else if (entry.hasGenre(selectedGenreId)) { titleStyle = sProgramTitleStyle; episodeStyle = sEpisodeTitleStyle; } if (TextUtils.isEmpty(title)) { title = getResources().getString(R.string.program_title_for_no_information); } if (mTableEntry.scheduledRecording != null) { //TODO(dvr): use a proper icon for UI status. title = "" + title; } SpannableStringBuilder description = new SpannableStringBuilder(); description.append(title); if (!TextUtils.isEmpty(episode)) { description.append('\n'); // Add a 'zero-width joiner'/ZWJ in order to ensure we have the same line height for // all lines. This is a non-printing character so it will not change the horizontal // spacing however it will affect the line height. As we ensure the ZWJ has the same // text style as the title it will make sure the line height is consistent. description.append('\u200D'); int middle = description.length(); description.append(episode); description.setSpan(titleStyle, 0, middle, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); description.setSpan(episodeStyle, middle, description.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else { description.setSpan(titleStyle, 0, description.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } setText(description); } measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); mTextWidth = getMeasuredWidth() - getPaddingStart() - getPaddingEnd(); int start = GuideUtils.convertMillisToPixel(entry.entryStartUtcMillis); int guideStart = GuideUtils.convertMillisToPixel(fromUtcMillis); layoutVisibleArea(guideStart - start); // Maximum width for us to use a ripple mMaxWidthForRipple = GuideUtils.convertMillisToPixel(fromUtcMillis, toUtcMillis); }
From source file:at.jclehner.rxdroid.DoseView.java
private void updateView() { mStatus = STATUS_INDETERMINATE;/*from w w w. ja va2s . c o m*/ mIntakeStatus.setImageDrawable(null); if (mDrug != null) { if (!mDrug.isActive()) mDoseText.setText("0"); else if (!mDisplayDose.isZero()) { setStatus(STATUS_TAKEN); SpannableStringBuilder sb = new SpannableStringBuilder(Util.prettify(mDisplayDose)); final Date lastScheduleUpdate = mDrug.getLastScheduleUpdateDate(); if (lastScheduleUpdate == null || !mDate.before(lastScheduleUpdate)) { final Fraction scheduledDose = mDrug.getDose(mDoseTime, mDate); int cmp = mDisplayDose.compareTo(scheduledDose); String suffix; if (cmp < 0) suffix = "-"; else if (cmp > 0) suffix = "+"; else suffix = null; if (suffix != null) { sb.append(suffix); sb.setSpan(new SuperscriptSpan(), sb.length() - 1, sb.length(), 0); } } mDoseText.setText(sb); } else { Fraction dose = mDrug.getDose(mDoseTime, mDate); mDoseText.setText(Util.prettify(dose)); if (mIntakeCount == 0) { if (!dose.isZero() && !mDrug.isAsNeeded()) { int offset = (int) Settings.getTrueDoseTimeEndOffset(mDoseTime); Date end = DateTime.add(mDate, Calendar.MILLISECOND, offset); if (DateTime.now().after(end)) setStatus(STATUS_MISSED); } } else setStatus(STATUS_IGNORED); } } else if (mDisplayDose != null) mDoseText.setText(Util.prettify(mDisplayDose)); if ("0".equals(mDoseText.getText())) { String zeroStr = null; if (BuildConfig.DEBUG) zeroStr = Settings.getString("doseview_zero"); if (zeroStr == null) zeroStr = "-"; mDoseText.setText(zeroStr); } }
From source file:tv.acfun.a63.CommentsActivity.java
@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { int count = mAdapter.getCount(); if (position > count) { if (isreload) { mFootview.findViewById(R.id.list_footview_progress).setVisibility(View.VISIBLE); TextView textview = (TextView) mFootview.findViewById(R.id.list_footview_text); textview.setText(R.string.loading); requestData(pageIndex, false); }/*from www.ja va2 s . c o m*/ return; } showBar(); // show input bar when selected comment Object o = parent.getItemAtPosition(position); if (o == null || !(o instanceof Comment)) return; Comment c = (Comment) o; int quoteCount = getQuoteCount(); removeQuote(mCommentText.getText()); if (quoteCount == c.count) return; // ? String pre = ":#" + c.count; mQuoteSpan = new Quote(c.count); /** * @see http * ://www.kpbird.com/2013/02/android-chips-edittext-token-edittext * .html */ SpannableStringBuilder sb = SpannableStringBuilder.valueOf(mCommentText.getText()); TextView tv = TextViewUtils.createBubbleTextView(this, pre); BitmapDrawable bd = (BitmapDrawable) TextViewUtils.convertViewToDrawable(tv); bd.setBounds(0, 0, bd.getIntrinsicWidth(), bd.getIntrinsicHeight()); sb.insert(0, pre); mQuoteImage = new ImageSpan(bd); sb.setSpan(mQuoteImage, 0, pre.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); sb.setSpan(mQuoteSpan, 0, pre.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); sb.append(""); mCommentText.setText(sb); mCommentText.setSelection(mCommentText.getText().length()); }
From source file:com.mattprecious.notisync.service.SecondaryService.java
/** * Taken and modified from AOSP MMS app. * src/com/android/mms/transaction/MessagingNotification.java *///ww w . j av a 2s . com private Notification buildRichNotification(NotificationCompat.Builder builder, List<List<NotificationData>> threadList, Bitmap photoIfSingleThread) { if (threadList.size() == 0) { return builder.build(); } final TextAppearanceSpan primarySpan = new TextAppearanceSpan(this, R.style.NotificationPrimaryText); final TextAppearanceSpan secondarySpan = new TextAppearanceSpan(this, R.style.NotificationSecondaryText); // only one thread if (threadList.size() == 1) { List<NotificationData> thread = threadList.get(0); NotificationData lastData = thread.get(thread.size() - 1); builder.setContentTitle(lastData.sender); if (photoIfSingleThread != null) { builder.setLargeIcon(resizePhoto(photoIfSingleThread)); } // only one message, display the whole thing if (thread.size() == 1) { String message = dedupeNewlines(lastData.message); builder.setContentText(message); return new NotificationCompat.BigTextStyle(builder).bigText(message) // Forcibly show the last line, with the smallIcon in // it, if we kicked the smallIcon out with a photo // bitmap .setSummaryText((photoIfSingleThread == null) ? null : " ").build(); } else { // multiple messages for the same thread SpannableStringBuilder buf = new SpannableStringBuilder(); boolean first = true; for (NotificationData data : thread) { // remove extra newlines String message = dedupeNewlines(data.message); if (first) { first = false; } else { buf.append('\n'); } buf.append(message); } builder.setContentTitle(getString(R.string.noti_title_new_messages, thread.size())); return new NotificationCompat.BigTextStyle(builder).bigText(buf) // Forcibly show the last line, with the smallIcon in // it, if we kicked the smallIcon out with a photo // bitmap .setSummaryText((photoIfSingleThread == null) ? null : " ").build(); } } else { // multiple threads String separator = ", "; SpannableStringBuilder contentStringBuilder = new SpannableStringBuilder(); boolean first = true; int totalMessageCount = 0; for (List<NotificationData> thread : threadList) { totalMessageCount += thread.size(); if (first) { first = false; } else { contentStringBuilder.append(separator); } NotificationData lastData = thread.get(thread.size() - 1); contentStringBuilder.append(lastData.sender); } builder.setContentTitle(getString(R.string.noti_title_new_messages, totalMessageCount)); builder.setContentText(contentStringBuilder); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder); // We have to set the summary text to non-empty so the content text // doesn't show up when expanded. inboxStyle.setSummaryText(" "); int c = 0; for (List<NotificationData> dataList : threadList) { if (c == 8) break; NotificationData lastData = dataList.get(dataList.size() - 1); SpannableStringBuilder inboxStringBuilder = new SpannableStringBuilder(); int senderLength = lastData.sender.length(); inboxStringBuilder.append(lastData.sender).append(": "); inboxStringBuilder.setSpan(primarySpan, 0, senderLength, 0); inboxStringBuilder.append(dedupeNewlines(lastData.message)); inboxStringBuilder.setSpan(secondarySpan, senderLength, senderLength + lastData.sender.length(), 0); inboxStyle.addLine(inboxStringBuilder); } return inboxStyle.build(); } }
From source file:com.android.mms.transaction.MessagingNotification.java
private static CharSequence formatSenders(Context context, ArrayList<NotificationInfo> senders) { final TextAppearanceSpan notificationSenderSpan = new TextAppearanceSpan(context, R.style.NotificationPrimaryText); String separator = context.getString(R.string.enumeration_comma); // ", " SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); int len = senders.size(); for (int i = 0; i < len; i++) { if (i > 0) { spannableStringBuilder.append(separator); }//w ww . j av a2 s .c om spannableStringBuilder.append(senders.get(i).mSender.getName()); } spannableStringBuilder.setSpan(notificationSenderSpan, 0, spannableStringBuilder.length(), 0); return spannableStringBuilder; }