List of usage examples for android.text SpannableStringBuilder append
public SpannableStringBuilder append(char text)
From source file:com.google.android.apps.location.gps.gnsslogger.PlotFragment.java
/** * Updates the CN0 versus Time plot data from a {@link GnssMeasurement} *///from ww w . ja v a2 s .c o m protected void updateCnoTab(GnssMeasurementsEvent event) { long timeInSeconds = TimeUnit.NANOSECONDS.toSeconds(event.getClock().getTimeNanos()); if (mInitialTimeSeconds < 0) { mInitialTimeSeconds = timeInSeconds; } // Building the texts message in analysis text view List<GnssMeasurement> measurements = sortByCarrierToNoiseRatio(new ArrayList<>(event.getMeasurements())); SpannableStringBuilder builder = new SpannableStringBuilder(); double currentAverage = 0; if (measurements.size() >= NUMBER_OF_STRONGEST_SATELLITES) { mAverageCn0 = (mAverageCn0 * mMeasurementCount + (measurements.get(0).getCn0DbHz() + measurements.get(1).getCn0DbHz() + measurements.get(2).getCn0DbHz() + measurements.get(3).getCn0DbHz()) / NUMBER_OF_STRONGEST_SATELLITES) / (++mMeasurementCount); currentAverage = (measurements.get(0).getCn0DbHz() + measurements.get(1).getCn0DbHz() + measurements.get(2).getCn0DbHz() + measurements.get(3).getCn0DbHz()) / NUMBER_OF_STRONGEST_SATELLITES; } builder.append(getString(R.string.history_average_hint, sDataFormat.format(mAverageCn0) + "\n")); builder.append(getString(R.string.current_average_hint, sDataFormat.format(currentAverage) + "\n")); for (int i = 0; i < NUMBER_OF_STRONGEST_SATELLITES && i < measurements.size(); i++) { int start = builder.length(); builder.append(mDataSetManager.getConstellationPrefix(measurements.get(i).getConstellationType()) + measurements.get(i).getSvid() + ": " + sDataFormat.format(measurements.get(i).getCn0DbHz()) + "\n"); int end = builder.length(); builder.setSpan( new ForegroundColorSpan(mColorMap.getColor(measurements.get(i).getSvid(), measurements.get(i).getConstellationType())), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } builder.append(getString(R.string.satellite_number_sum_hint, measurements.size())); mAnalysisView.setText(builder); // Adding incoming data into Dataset mLastTimeReceivedSeconds = timeInSeconds - mInitialTimeSeconds; for (GnssMeasurement measurement : measurements) { int constellationType = measurement.getConstellationType(); int svID = measurement.getSvid(); if (constellationType != GnssStatus.CONSTELLATION_UNKNOWN) { mDataSetManager.addValue(CN0_TAB, constellationType, svID, mLastTimeReceivedSeconds, measurement.getCn0DbHz()); } } mDataSetManager.fillInDiscontinuity(CN0_TAB, mLastTimeReceivedSeconds); // Checks if the plot has reached the end of frame and resize if (mLastTimeReceivedSeconds > mCurrentRenderer.getXAxisMax()) { mCurrentRenderer.setXAxisMax(mLastTimeReceivedSeconds); mCurrentRenderer.setXAxisMin(mLastTimeReceivedSeconds - TIME_INTERVAL_SECONDS); } mChartView.invalidate(); }
From source file:kr.wdream.storyshop.AndroidUtilities.java
public static CharSequence generateSearchName(String name, String name2, String q) { if (name == null && name2 == null) { return ""; }/*from w w w. j a v a2s .c om*/ SpannableStringBuilder builder = new SpannableStringBuilder(); String wholeString = name; if (wholeString == null || wholeString.length() == 0) { wholeString = name2; } else if (name2 != null && name2.length() != 0) { wholeString += " " + name2; } wholeString = wholeString.trim(); String lower = " " + wholeString.toLowerCase(); int index; int lastIndex = 0; while ((index = lower.indexOf(" " + q, lastIndex)) != -1) { int idx = index - (index == 0 ? 0 : 1); int end = q.length() + (index == 0 ? 0 : 1) + idx; if (lastIndex != 0 && lastIndex != idx + 1) { builder.append(wholeString.substring(lastIndex, idx)); } else if (lastIndex == 0 && idx != 0) { builder.append(wholeString.substring(0, idx)); } String query = wholeString.substring(idx, end); if (query.startsWith(" ")) { builder.append(" "); } query = query.trim(); builder.append(AndroidUtilities.replaceTags("<c#ff4d83b3>" + query + "</c>")); lastIndex = end; } if (lastIndex != -1 && lastIndex != wholeString.length()) { builder.append(wholeString.substring(lastIndex, wholeString.length())); } return builder; }
From source file:com.android.mms.ui.MessageListItem.java
private void bindCommonMessage(final boolean sameItem) { if (mDownloadButton != null) { mDownloadButton.setVisibility(View.GONE); mDownloading.setVisibility(View.GONE); }/*from w w w. jav a 2 s. c o m*/ // Since the message text should be concatenated with the sender's // address(or name), I have to display it here instead of // displaying it by the Presenter. mBodyTextView.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); boolean haveLoadedPdu = mMessageItem.isSms() || mMessageItem.mSlideshow != null; // Here we're avoiding reseting the avatar to the empty avatar when we're rebinding // to the same item. This happens when there's a DB change which causes the message item // cache in the MessageListAdapter to get cleared. When an mms MessageItem is newly // created, it has no info in it except the message id. The info is eventually loaded // and bindCommonMessage is called again (see onPduLoaded below). When we haven't loaded // the pdu, we don't want to call updateAvatarView because it // will set the avatar to the generic avatar then when this method is called again // from onPduLoaded, it will reset to the real avatar. This test is to avoid that flash. if (!sameItem || haveLoadedPdu) { boolean isSelf = Sms.isOutgoingFolder(mMessageItem.mBoxId); String addr = isSelf ? null : mMessageItem.mAddress; updateAvatarView(addr, isSelf); } // Add SIM sms address above body. if (isSimCardMessage()) { mSimMessageAddress.setVisibility(VISIBLE); SpannableStringBuilder buf = new SpannableStringBuilder(); if (mMessageItem.mBoxId == Sms.MESSAGE_TYPE_INBOX) { buf.append(mContext.getString(R.string.from_label)); } else { buf.append(mContext.getString(R.string.to_address_label)); } buf.append(Contact.get(mMessageItem.mAddress, true).getName()); mSimMessageAddress.setText(buf); } // Get and/or lazily set the formatted message from/on the // MessageItem. Because the MessageItem instances come from a // cache (currently of size ~50), the hit rate on avoiding the // expensive formatMessage() call is very high. CharSequence formattedMessage = mMessageItem.getCachedFormattedMessage(); if (formattedMessage == null) { formattedMessage = formatMessage(mMessageItem, mMessageItem.mBody, mMessageItem.mSubject, mMessageItem.mHighlight, mMessageItem.mTextContentType); mMessageItem.setCachedFormattedMessage(formattedMessage); } if (!sameItem || haveLoadedPdu) { mBodyTextView.setText(formattedMessage); } updateSimIndicatorView(mMessageItem.mSubId); // Debugging code to put the URI of the image attachment in the body of the list item. if (DEBUG) { String debugText = null; if (mMessageItem.mSlideshow == null) { debugText = "NULL slideshow"; } else { SlideModel slide = ((SlideshowModel) mMessageItem.mSlideshow).get(0); if (slide == null) { debugText = "NULL first slide"; } else if (!slide.hasImage()) { debugText = "Not an image"; } else { debugText = slide.getImage().getUri().toString(); } } mBodyTextView.setText(mPosition + ": " + debugText); } // If we're in the process of sending a message (i.e. pending), then we show a "SENDING..." // string in place of the timestamp. if (!sameItem || haveLoadedPdu) { boolean isCountingDown = mMessageItem.getCountDown() > 0 && MessagingPreferenceActivity.getMessageSendDelayDuration(mContext) > 0; int sendingTextResId = isCountingDown ? R.string.sent_countdown : R.string.sending_message; mDateView.setText(buildTimestampLine( mMessageItem.isSending() ? mContext.getResources().getString(sendingTextResId) : mMessageItem.mTimestamp)); } if (mMessageItem.isSms()) { showMmsView(false); mMessageItem.setOnPduLoaded(null); } else { if (DEBUG) { Log.v(TAG, "bindCommonMessage for item: " + mPosition + " " + mMessageItem.toString() + " mMessageItem.mAttachmentType: " + mMessageItem.mAttachmentType + " sameItem: " + sameItem); } if (mMessageItem.mAttachmentType != WorkingMessage.TEXT) { if (!sameItem) { setImage(null, null); } setOnClickListener(mMessageItem); drawPlaybackButton(mMessageItem); } else { showMmsView(false); } if (mMessageItem.mSlideshow == null) { final int mCurrentAttachmentType = mMessageItem.mAttachmentType; mMessageItem.setOnPduLoaded(new MessageItem.PduLoadedCallback() { public void onPduLoaded(MessageItem messageItem) { if (DEBUG) { Log.v(TAG, "PduLoadedCallback in MessageListItem for item: " + mPosition + " " + (mMessageItem == null ? "NULL" : mMessageItem.toString()) + " passed in item: " + (messageItem == null ? "NULL" : messageItem.toString())); } if (messageItem != null && mMessageItem != null && messageItem.getMessageId() == mMessageItem.getMessageId()) { mMessageItem.setCachedFormattedMessage(null); bindCommonMessage(mCurrentAttachmentType == messageItem.mAttachmentType); } } }); } else { if (mPresenter == null) { mPresenter = PresenterFactory.getPresenter("MmsThumbnailPresenter", mContext, this, mMessageItem.mSlideshow); } else { mPresenter.setModel(mMessageItem.mSlideshow); mPresenter.setView(this); } if (mImageLoadedCallback == null) { mImageLoadedCallback = new ImageLoadedCallback(this); } else { mImageLoadedCallback.reset(this); } mPresenter.present(mImageLoadedCallback); } } drawRightStatusIndicator(mMessageItem); requestLayout(); }
From source file:com.android.mms.quickmessage.QuickMessage.java
private CharSequence formatMessage(String message) { SpannableStringBuilder buf = new SpannableStringBuilder(); // Get the emojis preference SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); boolean enableEmojis = prefs.getBoolean(MessagingPreferenceActivity.ENABLE_EMOJIS, false); if (!TextUtils.isEmpty(message)) { SmileyParser parser = SmileyParser.getInstance(); CharSequence smileyBody = parser.addSmileySpans(message); if (enableEmojis) { EmojiParser emojiParser = EmojiParser.getInstance(); smileyBody = emojiParser.addEmojiSpans(smileyBody); }/* ww w.j a v a 2s . c om*/ buf.append(smileyBody); } return buf; }
From source file:com.hippo.ehviewer.ui.scene.FavoritesScene.java
private void updateSearchBar() { Context context = getContext2(); if (null == context || null == mUrlBuilder || null == mSearchBar || null == mFavCatArray) { return;// w w w. j av a 2 s . c o m } // Update title int favCat = mUrlBuilder.getFavCat(); String favCatName; if (favCat >= 0 && favCat < 10) { favCatName = mFavCatArray[favCat]; } else if (favCat == FavListUrlBuilder.FAV_CAT_LOCAL) { favCatName = getString(R.string.local_favorites); } else { favCatName = getString(R.string.cloud_favorites); } String keyword = mUrlBuilder.getKeyword(); if (TextUtils.isEmpty(keyword)) { if (!ObjectUtils.equal(favCatName, mOldFavCat)) { mSearchBar.setTitle(getString(R.string.favorites_title, favCatName)); } } else { if (!ObjectUtils.equal(favCatName, mOldFavCat) || !ObjectUtils.equal(keyword, mOldKeyword)) { mSearchBar.setTitle(getString(R.string.favorites_title_2, favCatName, keyword)); } } // Update hint if (!ObjectUtils.equal(favCatName, mOldFavCat)) { Drawable searchImage = DrawableManager.getDrawable(context, R.drawable.v_magnify_x24); SpannableStringBuilder ssb = new SpannableStringBuilder(" "); ssb.append(getString(R.string.favorites_search_bar_hint, favCatName)); int textSize = (int) (mSearchBar.getEditTextTextSize() * 1.25); if (searchImage != null) { searchImage.setBounds(0, 0, textSize, textSize); ssb.setSpan(new ImageSpan(searchImage), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } mSearchBar.setEditTextHint(ssb); } mOldFavCat = favCatName; mOldKeyword = keyword; // Save recent fav cat Settings.putRecentFavCat(mUrlBuilder.getFavCat()); }
From source file:com.fa.mastodon.activity.ComposeActivity.java
private void onUploadSuccess(final QueuedMedia item, Media media) { item.id = media.id;/*w w w.ja v a 2s . co m*/ /* Add the upload URL to the text field. Also, keep a reference to the span so if the user * chooses to remove the media, the URL is also automatically removed. */ item.uploadUrl = new URLSpan(media.textUrl); int end = 1 + media.textUrl.length(); SpannableStringBuilder builder = new SpannableStringBuilder(); builder.append(' '); builder.append(media.textUrl); builder.setSpan(item.uploadUrl, 0, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textEditor.append(builder); waitForMediaLatch.countDown(); }
From source file:com.mattprecious.notisync.service.SecondaryService.java
/** * Taken and modified from AOSP MMS app. * src/com/android/mms/transaction/MessagingNotification.java */// w w w . j a va2 s .c o m 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: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); }// w w w . ja v a 2 s. c om 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.kyakujin.android.autoeco.ui.MainActivity.java
/** * About//from w w w. j a v a 2 s. c om */ private void showAboutDialog() { PackageManager pm = this.getPackageManager(); String packageName = this.getPackageName(); String versionName; try { PackageInfo info = pm.getPackageInfo(packageName, 0); versionName = info.versionName; } catch (PackageManager.NameNotFoundException e) { versionName = "N/A"; } SpannableStringBuilder aboutBody = new SpannableStringBuilder(); SpannableString mailAddress = new SpannableString(getString(R.string.mailto)); mailAddress.setSpan(new ClickableSpan() { @Override public void onClick(View view) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_SENDTO); intent.setData(Uri.parse(getString(R.string.description_mailto))); intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.description_mail_subject)); startActivity(intent); } }, 0, mailAddress.length(), 0); aboutBody.append(Html.fromHtml(getString(R.string.about_body, versionName))); aboutBody.append("\n"); aboutBody.append(mailAddress); LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); TextView aboutBodyView = (TextView) layoutInflater.inflate(R.layout.fragment_about_dialog, null); aboutBodyView.setText(aboutBody); aboutBodyView.setMovementMethod(LinkMovementMethod.getInstance()); AlertDialog dlg = new AlertDialog.Builder(this).setTitle(R.string.alert_title_about).setView(aboutBodyView) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create(); dlg.show(); }
From source file:org.bobstuff.bobball.ActivityStateEnum.java
private void showWonScreen() { activityState = ActivityStateEnum.GAMEWON; Statistics.saveHighestLevel(numPlayers, gameManager.getLevel() + 1); levelSeries++;//from ww w . ja v a 2s . c o m Statistics.saveLongestSeries(levelSeries); GameState gs = gameManager.getCurrGameState(); Grid currGrid = gs.getGrid(); SpannableStringBuilder percentageCleared = new SpannableStringBuilder(); String percentageString = currGrid.getPercentCompleteFloat(1) + "%"; String totalPercentageString = getString(R.string.percentageCleared, percentageString); int player1Color = gs.getPlayer(1).getColor(); SpannableString percentage = new SpannableString(totalPercentageString); int percentageStart = totalPercentageString.length() - percentageString.length(); int percentageEnd = totalPercentageString.length(); percentage.setSpan(new ForegroundColorSpan(player1Color), percentageStart, percentageEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); percentageCleared.append(percentage); messageView.setText(getString(R.string.levelCompleted, gameManager.getLevel())); button.setText(R.string.nextLevel); retryButton.setVisibility(View.GONE); button.setVisibility(View.VISIBLE); backToLevelSelectButton.setVisibility(View.GONE); this.percentageCleared.setText(percentageCleared); this.percentageCleared.setVisibility(View.VISIBLE); if (numPlayers > 1) { totalPercentageCleared .setText(getString(R.string.totalPercentageCleared, currGrid.getPercentCompleteFloat() + "%")); totalPercentageCleared.setVisibility(View.VISIBLE); } bonusPoints.setText(getString(R.string.bonusPoints, gameManager.getBonusPoints(gs, gs.getPlayer(1)))); bonusPoints.setVisibility(View.VISIBLE); setMessageViewsVisible(true); }