Example usage for android.text SpannableString SpannableString

List of usage examples for android.text SpannableString SpannableString

Introduction

In this page you can find the example usage for android.text SpannableString SpannableString.

Prototype

public SpannableString(CharSequence source) 

Source Link

Document

For the backward compatibility reasons, this constructor copies all spans including android.text.NoCopySpan .

Usage

From source file:crackerjack.education.Indijisites.StartUp.java

private void render(Marker marker, View view) {
    int badge;//w ww.  java  2 s  .c o m
    if (marker.equals(mBrisbane)) {
        badge = R.drawable.badge_qld;
    } else {
        badge = 0;
    }
    ((ImageView) view.findViewById(R.id.badge)).setImageResource(badge);

    String title = marker.getTitle();
    TextView titleUi = ((TextView) view.findViewById(R.id.title));
    if (title != null) {
        // Spannable string allows us to edit the formatting of the text.
        SpannableString titleText = new SpannableString(title);
        titleText.setSpan(new ForegroundColorSpan(Color.RED), 0, titleText.length(), 0);
        titleUi.setText(titleText);
    } else {
        titleUi.setText("");
    }

    String snippet = marker.getSnippet();
    TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
    if (snippet != null && snippet.length() > 12) {
        SpannableString snippetText = new SpannableString(snippet);
        snippetText.setSpan(new ForegroundColorSpan(Color.BLUE), 0, snippet.length(), 0);
        snippetUi.setText(snippetText);
    } else {
        snippetUi.setText("");
    }
}

From source file:io.github.hidroh.materialistic.widget.StoryView.java

public void setPromoted(int change) {
    SpannableString spannable = new SpannableString(String.format(Locale.US, PROMOTED, change));
    spannable.setSpan(new SuperscriptSpan(), 0, spannable.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    spannable.setSpan(new RelativeSizeSpan(0.6f), 0, spannable.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    spannable.setSpan(new ForegroundColorSpan(mPromotedColorResId), 0, spannable.length(),
            Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    mRankTextView.append(spannable);/*from   w  w w.  j a  v  a 2s  .  co m*/
}

From source file:org.awesomeapp.messenger.ui.GalleryListItem.java

private SpannableString formatTimeStamp(Date date, int messageType, DateFormat format,
        GalleryListItem.DeliveryState delivery, EncryptionState encryptionState) {

    StringBuilder deliveryText = new StringBuilder();
    deliveryText.append(format.format(date));
    deliveryText.append(' ');

    if (delivery != null) {
        //this is for delivery
        if (delivery == DeliveryState.DELIVERED) {

            deliveryText.append(DELIVERED_SUCCESS);

        } else if (delivery == DeliveryState.UNDELIVERED) {

            deliveryText.append(DELIVERED_FAIL);
        }/*  w  w  w . j  ava  2 s . c o m*/
    }

    if (messageType != Imps.MessageType.POSTPONED)
        deliveryText.append(DELIVERED_SUCCESS);//this is for sent, so we know show 2 checks like WhatsApp!

    SpannableString spanText = null;

    if (encryptionState == EncryptionState.ENCRYPTED) {
        deliveryText.append('X');
        spanText = new SpannableString(deliveryText.toString());
        int len = spanText.length();

        spanText.setSpan(new ImageSpan(getContext(), R.drawable.ic_lock_outline_black_18dp), len - 1, len,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    } else if (encryptionState == EncryptionState.ENCRYPTED_AND_VERIFIED) {
        deliveryText.append('X');
        spanText = new SpannableString(deliveryText.toString());
        int len = spanText.length();

        spanText.setSpan(new ImageSpan(getContext(), R.drawable.ic_lock_outline_black_18dp), len - 1, len,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    } else {
        spanText = new SpannableString(deliveryText.toString());
        int len = spanText.length();

    }

    //   spanText.setSpan(new StyleSpan(Typeface.SANS_SERIF), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    // spanText.setSpan(new RelativeSizeSpan(0.8f), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    //    spanText.setSpan(new ForegroundColorSpan(R.color.soft_grey),
    //        0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    return spanText;
}

From source file:org.iota.wallet.ui.fragment.NodeInfoFragment.java

private SpannableString generateCenterSpannableText() {
    SpannableString s = new SpannableString(getString(R.string.transactions));
    s.setSpan(new RelativeSizeSpan(0.75f), 0, 0, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    s.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getActivity(), R.color.colorAccent)), 0,
            s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return s;/*from w  w w  .  ja v  a  2s.co m*/
}

From source file:org.navitproject.navit.Navit.java

private void showInfos() {
    SharedPreferences settings = getSharedPreferences(NAVIT_PREFS, MODE_PRIVATE);
    boolean firstStart = settings.getBoolean("firstStart", true);

    if (firstStart) {
        AlertDialog.Builder infobox = new AlertDialog.Builder(this);
        infobox.setTitle(getString(R.string.initial_info_box_title)); // TRANS
        infobox.setCancelable(false);/*from   www.j  av a  2s .  c  o m*/
        final TextView message = new TextView(this);
        message.setFadingEdgeLength(20);
        message.setVerticalFadingEdgeEnabled(true);
        // message.setVerticalScrollBarEnabled(true);
        RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);

        message.setLayoutParams(rlp);
        final SpannableString s = new SpannableString(getString(R.string.initial_info_box_message)); // TRANS
        Linkify.addLinks(s, Linkify.WEB_URLS);
        message.setText(s);
        message.setMovementMethod(LinkMovementMethod.getInstance());
        infobox.setView(message);

        // TRANS
        infobox.setPositiveButton(getString(R.string.initial_info_box_OK),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        Log.e("Navit", "Ok, user saw the infobox");
                    }
                });

        // TRANS
        infobox.setNeutralButton(getString(R.string.initial_info_box_more_info),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        Log.e("Navit", "user wants more info, show the website");
                        String url = "http://wiki.navit-project.org/index.php/Navit_on_Android";
                        Intent i = new Intent(Intent.ACTION_VIEW);
                        i.setData(Uri.parse(url));
                        startActivity(i);
                    }
                });
        infobox.show();
        SharedPreferences.Editor edit_settings = settings.edit();
        edit_settings.putBoolean("firstStart", false);
        edit_settings.commit();
    }
}

From source file:org.de.jmg.learn.SettingsActivity.java

public void init(boolean blnRestart) throws Exception {
    if (_Intent == null || _main == null || SettingsView == null || _blnInitialized) {
        return;// w w w  .  j  av a  2  s . c o  m
    }
    try {
        //lib.ShowToast(_main, "Settings Start");

        RelativeLayout layout = (RelativeLayout) findViewById(R.id.layoutSettings); // id fetch from xml
        ShapeDrawable rectShapeDrawable = new ShapeDrawable(); // pre defined class
        int pxPadding = lib.dpToPx(10);
        rectShapeDrawable.setPadding(pxPadding, pxPadding, pxPadding,
                pxPadding * ((lib.NookSimpleTouch()) ? 2 : 1));
        Paint paint = rectShapeDrawable.getPaint();
        paint.setColor(Color.BLACK);
        paint.setStyle(Style.STROKE);
        paint.setStrokeWidth(5); // you can change the value of 5
        lib.setBg(layout, rectShapeDrawable);

        mainView = _main.findViewById(Window.ID_ANDROID_CONTENT);
        //Thread.setDefaultUncaughtExceptionHandler(ErrorHandler);
        prefs = _main.getPreferences(Context.MODE_PRIVATE);

        TextView txtSettings = (TextView) findViewById(R.id.txtSettings);
        SpannableString Settings = new SpannableString(txtSettings.getText());
        Settings.setSpan(new UnderlineSpan(), 0, Settings.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        txtSettings.setText(Settings);
        initCheckBoxes();
        initSpinners(blnRestart);
        initButtons();
        initHelp();
        edDataDir = (EditText) findViewById(R.id.edDataDir);
        edDataDir.setSingleLine(true);
        edDataDir.setText(_main.JMGDataDirectory);
        edDataDir.setImeOptions(EditorInfo.IME_ACTION_DONE);
        edDataDir.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    String strDataDir = edDataDir.getText().toString();
                    File fileSelected = new File(strDataDir);
                    if (fileSelected.isDirectory() && fileSelected.exists()) {
                        _main.setJMGDataDirectory(fileSelected.getPath());
                        edDataDir.setText(_main.JMGDataDirectory);
                        Editor editor = prefs.edit();
                        editor.putString("JMGDataDirectory", fileSelected.getPath());
                        editor.commit();
                    }
                }
                return true;
            }
        });
        edDataDir.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ShowDataDirDialog();
                return true;
            }
        });
        if (!(lib.NookSimpleTouch()) && !_main.isSmallDevice) {
            SettingsView.getViewTreeObserver()
                    .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

                        @Override
                        public void onGlobalLayout() {
                            // Ensure you call it only once :
                            lib.removeLayoutListener(SettingsView.getViewTreeObserver(), this);

                            // Here you can get the size :)
                            resize(0);
                            //lib.ShowToast(_main, "Resize End");
                        }
                    });

        } else {
            //resize(1.8f);
            mScale = 1.0f;
        }
        _blnInitialized = true;
    } catch (Exception ex) {
        lib.ShowException(_main, ex);
    }

}

From source file:info.guardianproject.otr.app.im.app.MessageView.java

public void bindIncomingMessage(int id, int messageType, String address, String nickname, final String mimeType,
        final String body, Date date, Markup smileyRes, boolean scrolling, EncryptionState encryption,
        boolean showContact, int presenceStatus) {

    mHolder = (ViewHolder) getTag();//  w  w  w .  ja v  a2 s  .  c  o  m

    mHolder.mTextViewForMessages.setVisibility(View.VISIBLE);

    if (nickname == null)
        nickname = address;

    if (showContact && nickname != null) {
        lastMessage = nickname + ": " + formatMessage(body);
        showAvatar(address, nickname, true, presenceStatus);
    } else {
        lastMessage = formatMessage(body);
        showAvatar(address, nickname, true, presenceStatus);

        mHolder.resetOnClickListenerMediaThumbnail();
        if (mimeType != null) {

            mHolder.mTextViewForMessages.setVisibility(View.GONE);
            mHolder.mMediaThumbnail.setVisibility(View.VISIBLE);

            Uri mediaUri = Uri.parse(body);
            lastMessage = "";
            showMediaThumbnail(mimeType, mediaUri, id, mHolder);

        } else {
            mHolder.mMediaThumbnail.setVisibility(View.GONE);
            if (showContact) {
                String[] nickParts = nickname.split("/");

                lastMessage = nickParts[nickParts.length - 1] + ": " + formatMessage(body);

            } else {
                lastMessage = formatMessage(body);
            }
        }
    }

    if (lastMessage.length() > 0) {
        try {
            SpannableString spannablecontent = new SpannableString(lastMessage);
            EmojiManager.getInstance(getContext()).addEmoji(getContext(), spannablecontent);

            mHolder.mTextViewForMessages.setText(spannablecontent);
        } catch (IOException e) {
            LogCleaner.error(ImApp.LOG_TAG, "error processing message", e);
        }
    } else {
        mHolder.mTextViewForMessages.setText(lastMessage);
    }

    if (date != null) {
        CharSequence tsText = null;

        if (isSameDay(date, DATE_NOW))
            tsText = formatTimeStamp(date, messageType, MESSAGE_TIME_FORMAT, null, encryption);
        else
            tsText = formatTimeStamp(date, messageType, MESSAGE_DATETIME_FORMAT, null, encryption);

        mHolder.mTextViewForTimestamp.setText(tsText);
        mHolder.mTextViewForTimestamp.setVisibility(View.VISIBLE);

    } else {

        mHolder.mTextViewForTimestamp.setText("");
        //mHolder.mTextViewForTimestamp.setVisibility(View.GONE);

    }
    if (linkify)
        LinkifyHelper.addLinks(mHolder.mTextViewForMessages, new URLSpanConverter());
    LinkifyHelper.addTorSafeLinks(mHolder.mTextViewForMessages);
}

From source file:android.support.text.emoji.EmojiProcessor.java

/**
 * Checks a given CharSequence for emojis, and adds EmojiSpans if any emojis are found.
 * <p>// www  . j a  v a 2  s .co m
 * <ul>
 * <li>If no emojis are found, {@code charSequence} given as the input is returned without
 * any changes. i.e. charSequence is a String, and no emojis are found, the same String is
 * returned.</li>
 * <li>If the given input is not a Spannable (such as String), and at least one emoji is found
 * a new {@link android.text.Spannable} instance is returned. </li>
 * <li>If the given input is a Spannable, the same instance is returned. </li>
 * </ul>
 *
 * @param charSequence CharSequence to add the EmojiSpans, cannot be {@code null}
 * @param start start index in the charSequence to look for emojis, should be greater than or
 *              equal to {@code 0}, also less than {@code charSequence.length()}
 * @param end end index in the charSequence to look for emojis, should be greater than or
 *            equal to {@code start} parameter, also less than {@code charSequence.length()}
 * @param maxEmojiCount maximum number of emojis in the {@code charSequence}, should be greater
 *                      than or equal to {@code 0}
 * @param replaceAll whether to replace all emoji with {@link EmojiSpan}s
 */
CharSequence process(@NonNull final CharSequence charSequence, @IntRange(from = 0) int start,
        @IntRange(from = 0) int end, @IntRange(from = 0) int maxEmojiCount, final boolean replaceAll) {
    final boolean isSpannableBuilder = charSequence instanceof SpannableBuilder;
    if (isSpannableBuilder) {
        ((SpannableBuilder) charSequence).beginBatchEdit();
    }

    try {
        Spannable spannable = null;
        // if it is a spannable already, use the same instance to add/remove EmojiSpans.
        // otherwise wait until the the first EmojiSpan found in order to change the result
        // into a Spannable.
        if (isSpannableBuilder || charSequence instanceof Spannable) {
            spannable = (Spannable) charSequence;
        }

        if (spannable != null) {
            final EmojiSpan[] spans = spannable.getSpans(start, end, EmojiSpan.class);
            if (spans != null && spans.length > 0) {
                // remove existing spans, and realign the start, end according to spans
                // if start or end is in the middle of an emoji they should be aligned
                final int length = spans.length;
                for (int index = 0; index < length; index++) {
                    final EmojiSpan span = spans[index];
                    final int spanStart = spannable.getSpanStart(span);
                    final int spanEnd = spannable.getSpanEnd(span);
                    // Remove span only when its spanStart is NOT equal to current end.
                    // During add operation an emoji at index 0 is added with 0-1 as start and
                    // end indices. Therefore if there are emoji spans at [0-1] and [1-2]
                    // and end is 1, the span between 0-1 should be deleted, not 1-2.
                    if (spanStart != end) {
                        spannable.removeSpan(span);
                    }
                    start = Math.min(spanStart, start);
                    end = Math.max(spanEnd, end);
                }
            }
        }

        if (start == end || start >= charSequence.length()) {
            return charSequence;
        }

        // calculate max number of emojis that can be added. since getSpans call is a relatively
        // expensive operation, do it only when maxEmojiCount is not unlimited.
        if (maxEmojiCount != EmojiCompat.EMOJI_COUNT_UNLIMITED && spannable != null) {
            maxEmojiCount -= spannable.getSpans(0, spannable.length(), EmojiSpan.class).length;
        }
        // add new ones
        int addedCount = 0;
        final ProcessorSm sm = new ProcessorSm(mMetadataRepo.getRootNode());

        int currentOffset = start;
        int codePoint = Character.codePointAt(charSequence, currentOffset);

        while (currentOffset < end && addedCount < maxEmojiCount) {
            final int action = sm.check(codePoint);

            switch (action) {
            case ACTION_ADVANCE_BOTH:
                start += Character.charCount(Character.codePointAt(charSequence, start));
                currentOffset = start;
                if (currentOffset < end) {
                    codePoint = Character.codePointAt(charSequence, currentOffset);
                }
                break;
            case ACTION_ADVANCE_END:
                currentOffset += Character.charCount(codePoint);
                if (currentOffset < end) {
                    codePoint = Character.codePointAt(charSequence, currentOffset);
                }
                break;
            case ACTION_FLUSH:
                if (replaceAll || !hasGlyph(charSequence, start, currentOffset, sm.getFlushMetadata())) {
                    if (spannable == null) {
                        spannable = new SpannableString(charSequence);
                    }
                    addEmoji(spannable, sm.getFlushMetadata(), start, currentOffset);
                    addedCount++;
                }
                start = currentOffset;
                break;
            }
        }

        // After the last codepoint is consumed the state machine might be in a state where it
        // identified an emoji before. i.e. abc[women-emoji] when the last codepoint is consumed
        // state machine is waiting to see if there is an emoji sequence (i.e. ZWJ).
        // Need to check if it is in such a state.
        if (sm.isInFlushableState() && addedCount < maxEmojiCount) {
            if (replaceAll || !hasGlyph(charSequence, start, currentOffset, sm.getCurrentMetadata())) {
                if (spannable == null) {
                    spannable = new SpannableString(charSequence);
                }
                addEmoji(spannable, sm.getCurrentMetadata(), start, currentOffset);
                addedCount++;
            }
        }
        return spannable == null ? charSequence : spannable;
    } finally {
        if (isSpannableBuilder) {
            ((SpannableBuilder) charSequence).endBatchEdit();
        }
    }
}

From source file:io.github.hidroh.materialistic.data.HackerNewsItem.java

@Override
public Spannable getDisplayedTime(Context context) {
    if (displayedTime == null) {
        SpannableStringBuilder builder = new SpannableStringBuilder(
                dead ? context.getString(R.string.dead_prefix) + " " : "");
        SpannableString timeSpannable = new SpannableString(AppUtils.getAbbreviatedTimeSpan(time * 1000));
        if (deleted) {
            timeSpannable.setSpan(new StrikethroughSpan(), 0, timeSpannable.length(),
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }//from   w w w.j a v a 2 s. co  m
        builder.append(timeSpannable);
        displayedTime = builder;
    }
    return displayedTime;
}

From source file:it.gulch.linuxday.android.services.AlarmIntentService.java

private void notifyEvent(Intent intent) {
    long eventId = Long.parseLong(intent.getDataString());
    Event event = eventManager.get(eventId);
    if (event == null) {
        return;//from www. java2s . c om
    }

    //      NotificationManager notificationManager = (NotificationManager) getSystemService(Context
    // .NOTIFICATION_SERVICE);

    //      PendingIntent eventPendingIntent =
    //            TaskStackBuilder.create(this).addNextIntent(new Intent(this,
    // MainActivity.class)).addNextIntent(
    //                  new Intent(this, EventDetailsActivity.class).setData(Uri.parse(String.valueOf(event
    // .getId()))))
    //                  .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    PendingIntent eventPendingIntent = TaskStackBuilder.create(this)
            .addNextIntent(new Intent(this, MainActivity.class))
            .addNextIntent(new Intent(this, EventDetailsActivity.class)
                    .setData(Uri.parse(String.valueOf(event.getId()))))
            .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    int defaultFlags = Notification.DEFAULT_SOUND;
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    if (sharedPreferences.getBoolean(SettingsFragment.KEY_PREF_NOTIFICATIONS_VIBRATE, false)) {
        defaultFlags |= Notification.DEFAULT_VIBRATE;
    }

    String trackName = event.getTrack().getTitle();
    CharSequence bigText;
    String contentText;
    if (CollectionUtils.isEmpty(event.getPeople())) {
        contentText = trackName;
        bigText = event.getSubtitle();
    } else {
        String personsSummary = StringUtils.join(event.getPeople(), ", ");
        contentText = String.format("%1$s - %2$s", trackName, personsSummary);
        String subTitle = event.getSubtitle();

        SpannableString spannableBigText;
        if (TextUtils.isEmpty(subTitle)) {
            spannableBigText = new SpannableString(personsSummary);
        } else {
            spannableBigText = new SpannableString(String.format("%1$s\n%2$s", subTitle, personsSummary));
        }

        // Set the persons summary in italic
        spannableBigText.setSpan(new StyleSpan(Typeface.ITALIC),
                +spannableBigText.length() - personsSummary.length(), spannableBigText.length(),
                +Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        bigText = spannableBigText;
    }

    String roomName = event.getTrack().getRoom().getName();
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher).setWhen(event.getStartDate().getTime())
            .setContentTitle(event.getTitle()).setContentText(contentText)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(bigText).setSummaryText(trackName))
            .setContentInfo(roomName).setContentIntent(eventPendingIntent).setAutoCancel(true)
            .setDefaults(defaultFlags).setPriority(NotificationCompat.PRIORITY_HIGH);

    // Blink the LED with FOSDEM color if enabled in the options
    if (sharedPreferences.getBoolean(SettingsFragment.KEY_PREF_NOTIFICATIONS_LED, false)) {
        notificationBuilder.setLights(getResources().getColor(R.color.maincolor), 1000, 5000);
    }

    /*// Android Wear extensions
    NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender();
            
    // Add an optional action button to show the room map image
    int roomImageResId = getResources()
    .getIdentifier(StringUtils.roomNameToResourceName(roomName), "drawable", getPackageName());
    if(roomImageResId != 0) {
       // The room name is the unique Id of a RoomImageDialogActivity
       Intent mapIntent = new Intent(this, RoomImageDialogActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
       .setData(Uri.parse(roomName));
       mapIntent.putExtra(RoomImageDialogActivity.EXTRA_ROOM_NAME, roomName);
       mapIntent.putExtra(RoomImageDialogActivity.EXTRA_ROOM_IMAGE_RESOURCE_ID, roomImageResId);
       PendingIntent mapPendingIntent =
       PendingIntent.getActivity(this, 0, mapIntent, PendingIntent.FLAG_UPDATE_CURRENT);
       CharSequence mapTitle = getString(R.string.room_map);
       notificationBuilder
       .addAction(new NotificationCompat.Action(R.drawable.ic_action_place, mapTitle, mapPendingIntent));
       // Use bigger action icon for wearable notification
       wearableExtender.addAction(
       new NotificationCompat.Action(R.drawable.ic_place_white_wear, mapTitle, mapPendingIntent));
    }
            
    notificationBuilder.extend(wearableExtender);*/

    NotificationManagerCompat.from(this).notify((int) eventId, notificationBuilder.build());
}