Example usage for android.text.style StyleSpan StyleSpan

List of usage examples for android.text.style StyleSpan StyleSpan

Introduction

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

Prototype

public StyleSpan(@NonNull Parcel src) 

Source Link

Document

Creates a StyleSpan from a parcel.

Usage

From source file:com.zulip.android.util.CustomHtmlToSpannedConverter.java

private void handleEndTag(String tag) {
    if (tag.equalsIgnoreCase("br")) {
        handleBr(mSpannableStringBuilder);
    } else if (tag.equalsIgnoreCase("p")) {
        handleP(mSpannableStringBuilder);
    } else if (tag.equalsIgnoreCase("div")) {
        handleP(mSpannableStringBuilder);
    } else if (tag.equalsIgnoreCase("strong")) {
        end(mSpannableStringBuilder, Bold.class, new StyleSpan(Typeface.BOLD));
    } else if (tag.equalsIgnoreCase("b")) {
        end(mSpannableStringBuilder, Bold.class, new StyleSpan(Typeface.BOLD));
    } else if (tag.equalsIgnoreCase("em")) {
        end(mSpannableStringBuilder, Italic.class, new StyleSpan(Typeface.ITALIC));
    } else if (tag.equalsIgnoreCase("cite")) {
        end(mSpannableStringBuilder, Italic.class, new StyleSpan(Typeface.ITALIC));
    } else if (tag.equalsIgnoreCase("dfn")) {
        end(mSpannableStringBuilder, Italic.class, new StyleSpan(Typeface.ITALIC));
    } else if (tag.equalsIgnoreCase("i")) {
        end(mSpannableStringBuilder, Italic.class, new StyleSpan(Typeface.ITALIC));
    } else if (tag.equalsIgnoreCase("big")) {
        end(mSpannableStringBuilder, Big.class, new RelativeSizeSpan(1.25f));
    } else if (tag.equalsIgnoreCase("small")) {
        end(mSpannableStringBuilder, Small.class, new RelativeSizeSpan(0.8f));
    } else if (tag.equalsIgnoreCase("font")) {
        endFont(mSpannableStringBuilder);
    } else if (tag.equalsIgnoreCase("blockquote")) {
        handleP(mSpannableStringBuilder);
        end(mSpannableStringBuilder, Blockquote.class, new CustomQuoteSpan());
    } else if (tag.equalsIgnoreCase("tt")) {
        end(mSpannableStringBuilder, Monospace.class, new TypefaceSpan(MONOSPACE));
    } else if (tag.equalsIgnoreCase("a")) {
        endA(mSpannableStringBuilder);//www  . j  ava2  s.c om
    } else if (tag.equalsIgnoreCase("span")) {
        endSpan(mSpannableStringBuilder);
    } else if (tag.equalsIgnoreCase("u")) {
        end(mSpannableStringBuilder, Underline.class, new UnderlineSpan());
    } else if (tag.equalsIgnoreCase("sup")) {
        end(mSpannableStringBuilder, Super.class, new SuperscriptSpan());
    } else if (tag.equalsIgnoreCase("sub")) {
        end(mSpannableStringBuilder, Sub.class, new SubscriptSpan());
    } else if (tag.equalsIgnoreCase("code")) {
        endMultiple(mSpannableStringBuilder, InlineCode.class,
                new Object[] { new TypefaceSpan(MONOSPACE), new ForegroundColorSpan(0xffdd1144) // pink
                });
    } else if (tag.equalsIgnoreCase("pre")) {
        end(mSpannableStringBuilder, CodeBlock.class, new TypefaceSpan(MONOSPACE));
    } else if (tag.length() == 2 && Character.toLowerCase(tag.charAt(0)) == 'h' && tag.charAt(1) >= '1'
            && tag.charAt(1) <= '6') {
        handleP(mSpannableStringBuilder);
        endHeader(mSpannableStringBuilder);
    } else if (mTagHandler != null) {
        mTagHandler.handleTag(false, tag, mSpannableStringBuilder, mReader);
    }
}

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;// ww w  .j  a va  2s  .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());
}

From source file:com.groksolutions.grok.mobile.annotation.AnnotationListFragment.java

/**
 * Format annotation message body for list item display
 *
 * @param annotation The annotation to format
 *
 * @return The formatted annotation text suitable for use with {@link android.widget.TextView}
 *//* w  w  w.ja v a2 s  .  c o  m*/
SpannableStringBuilder formatAnnotationBody(Annotation annotation) {
    int pos;

    // Format text
    SpannableStringBuilder text = new SpannableStringBuilder();

    // <br/> My Message
    pos = text.length();
    text.append(annotation.getMessage());
    text.setSpan(new RelativeSizeSpan(1.0f), pos, text.length(), 0);
    text.setSpan(new StyleSpan(Typeface.NORMAL), pos, text.length(), 0);

    // Attach hidden annotation ID to the text.
    // This ID is used by the actions attached to the list
    text.setSpan(new android.text.Annotation("id", annotation.getId()), 0, text.length(), 0);

    return text;
}

From source file:eu.power_switch.widget.activity.ConfigureReceiverWidgetActivity.java

private void saveCurrentConfiguration() {
    try {//  w w w.j av  a 2s . co m
        // First, get the App Widget ID from the Intent that launched the Activity:
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null && extras.containsKey(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
            int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            // Perform your App Widget configuration:
            Apartment selectedApartment = getSelectedApartment();
            Room selectedRoom = selectedApartment.getRoom(spinnerRoom.getSelectedItem().toString());
            Receiver selectedReceiver = selectedRoom.getReceiver(spinnerReceiver.getSelectedItem().toString());

            // save new widget data to database
            ReceiverWidget receiverWidget = new ReceiverWidget(appWidgetId, selectedRoom.getId(),
                    selectedReceiver.getId());
            DatabaseHandler.addReceiverWidget(receiverWidget);
            // When the configuration is complete, get an instance of
            // the AppWidgetManager by calling getInstance(Context):
            AppWidgetManager appWidgetManager = AppWidgetManager
                    .getInstance(ConfigureReceiverWidgetActivity.this);
            // Update the App Widget with a RemoteViews layout by
            // calling updateAppWidget(int, RemoteViews):
            RemoteViews remoteViews = new RemoteViews(getString(eu.power_switch.shared.R.string.PACKAGE_NAME),
                    R.layout.widget_receiver);

            LinkedList<Button> buttons = selectedReceiver.getButtons();

            remoteViews.setTextViewText(R.id.textView_receiver_widget_name, selectedApartment.getName() + ": "
                    + selectedRoom.getName() + ": " + selectedReceiver.getName());

            int buttonOffset = 0;
            for (Button button : buttons) {
                // set button action
                RemoteViews buttonView = new RemoteViews(
                        getString(eu.power_switch.shared.R.string.PACKAGE_NAME),
                        R.layout.widget_receiver_button_layout);
                SpannableString s = new SpannableString(button.getName());
                s.setSpan(new StyleSpan(Typeface.BOLD), 0, button.getName().length(), 0);
                buttonView.setTextViewText(R.id.button_widget_universal, s);

                if (SmartphonePreferencesHandler.getHighlightLastActivatedButton()
                        && selectedReceiver.getLastActivatedButtonId().equals(button.getId())) {
                    buttonView.setTextColor(R.id.button_widget_universal,
                            ContextCompat.getColor(getApplicationContext(), R.color.color_light_blue_a700));
                }

                PendingIntent pendingIntent = WidgetIntentReceiver.buildReceiverWidgetActionPendingIntent(
                        getApplicationContext(), selectedApartment, selectedRoom, selectedReceiver, button,
                        appWidgetId * 15 + buttonOffset);

                buttonView.setOnClickPendingIntent(R.id.button_widget_universal, pendingIntent);

                remoteViews.addView(R.id.linearlayout_receiver_widget, buttonView);
                buttonOffset++;
            }

            appWidgetManager.updateAppWidget(appWidgetId, remoteViews);

            // Finally, create the return Intent, set it with the
            // Activity result, and finish the Activity:
            Intent resultValue = new Intent();
            resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
            setResult(RESULT_OK, resultValue);
            finish();
        }
    } catch (Exception e) {
        StatusMessageHandler.showErrorMessage(this, e);
    }
}

From source file:fr.tvbarthel.attempt.googlyzooapp.MainActivity.java

@Override
public void onNavigationDrawerItemSelected(GooglyPetEntry petSelected) {
    final int googlyName = petSelected.getName();
    mSelectedGooglyPet = petSelected.getPetId();

    final String petName = getResources().getString(googlyName);
    final String oogly = getResources().getString(R.string.googly_name_ext);
    mTitle = new SpannableString(getResources().getString(googlyName) + oogly);
    mTitle.setSpan(new StyleSpan(Typeface.BOLD), 0, petName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    mTitle.setSpan(new TypefaceSpan("sans-serif-light"), petName.length() - 1, mTitle.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    mActionBarIcon = petSelected.getBlackAndWhiteIcon();

    if (mPetTrackerFragment != null) {
        mPetTrackerFragment.setGooglyPet(mSelectedGooglyPet);
    }/*from   w  ww  .j  a v a 2  s .  c  o m*/
}

From source file:com.money.manager.ex.core.Core.java

/**
 * This method allows to highlight in bold the content of a search string
 * @param search       string//  ww w  .  j a  v  a 2  s .c  om
 * @param originalText string where to find
 * @return CharSequence modified
 */
public CharSequence highlight(String search, String originalText) {
    if (TextUtils.isEmpty(search))
        return originalText;
    // ignore case and accents
    // the same thing should have been done for the search text
    String normalizedText = Normalizer.normalize(originalText, Normalizer.Form.NFD)
            .replaceAll("\\p{InCombiningDiacriticalMarks}+", "").toLowerCase();

    int start = normalizedText.indexOf(search.toLowerCase());
    if (start < 0) {
        // not found, nothing to to
        return originalText;
    } else {
        // highlight each appearance in the original text
        // while searching in normalized text
        Spannable highlighted = new SpannableString(originalText);
        while (start >= 0) {
            int spanStart = Math.min(start, originalText.length());
            int spanEnd = Math.min(start + search.length(), originalText.length());

            highlighted.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), spanStart, spanEnd,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            start = normalizedText.indexOf(search, spanEnd);
        }
        return highlighted;
    }
}

From source file:com.microsoft.rightsmanagement.ui.widget.UserPolicyViewerFragment.java

/**
 * Updates the policy viewer according to the ownership
 *///from www . ja  va 2  s  .c o  m
private void updateViewAccordingToOwnership() {
    UserPolicyModel userPolicyModel = mUserPolicyDataProvider.getUserPolicyModel();
    // if this is not owner just show the rights with no header
    if (userPolicyModel.isIssuedToOwner()) {
        Logger.d(TAG, "user is the owner of user policy");
        mUpperTitleTextView.setText(getString(R.string.policy_viewer_owner_content));
        mOwnerNameTextView.setVisibility(View.GONE);
        setPolicyEditingButtonViewState(mUserPolicyDataProvider.isUserPolicyEditingEnabled());
    } else {
        Logger.d(TAG, "user is not the owner of user policy");
        //ignore input of allowing edit enabled and hide policy edit button 
        setPolicyEditingButtonViewState(false);
        mUpperTitleTextView.setText(R.string.policy_viewer_non_owner_content);
        SpannableStringBuilder sb = new SpannableStringBuilder();
        String grantedBy = getString(R.string.granted_by_string);
        sb.append(grantedBy);
        sb.append(" ");
        sb.append(userPolicyModel.getOwner());
        sb.setSpan(new StyleSpan(Typeface.BOLD), grantedBy.length(), sb.length(), 0);
        mOwnerNameTextView.setText(sb);
        drawRights();
    }
}

From source file:org.fdroid.enigtext.notifications.MessageNotifier.java

private static NotificationState constructNotificationState(Context context, MasterSecret masterSecret,
        Cursor cursor) {/*from  w w w . ja v  a2s  . c o  m*/
    NotificationState notificationState = new NotificationState();
    MessageRecord record;
    MmsSmsDatabase.Reader reader;

    if (masterSecret == null)
        reader = DatabaseFactory.getMmsSmsDatabase(context).readerFor(cursor);
    else
        reader = DatabaseFactory.getMmsSmsDatabase(context).readerFor(cursor, masterSecret);

    while ((record = reader.getNext()) != null) {
        Recipient recipient = record.getIndividualRecipient();
        Recipients recipients = record.getRecipients();
        long threadId = record.getThreadId();
        SpannableString body = record.getDisplayBody();
        Uri image = null;

        // XXXX This is so fucked up.  FIX ME!
        if (body.toString().equals(context.getString(R.string.MessageDisplayHelper_decrypting_please_wait))) {
            body = new SpannableString(context.getString(R.string.MessageNotifier_encrypted_message));
            body.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, body.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        notificationState.addNotification(new NotificationItem(recipient, recipients, threadId, body, image));
    }

    reader.close();
    return notificationState;
}

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

@NonNull
private SpannableString createAuthorSpannable(boolean authorLink) {
    SpannableString bySpannable = new SpannableString(AUTHOR_SEPARATOR + by);
    if (!authorLink) {
        return bySpannable;
    }/* w w  w. ja va 2s  .co  m*/
    bySpannable.setSpan(new StyleSpan(Typeface.BOLD), AUTHOR_SEPARATOR.length(), bySpannable.length(),
            Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View view) {
            view.getContext()
                    .startActivity(new Intent(Intent.ACTION_VIEW).setData(AppUtils.createUserUri(getBy())));
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
        }
    };
    bySpannable.setSpan(clickableSpan, AUTHOR_SEPARATOR.length(), bySpannable.length(),
            Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    return bySpannable;
}

From source file:com.limewoodmedia.nsdroid.activities.World.java

private void doSetup() {
    // Region name
    regionName.setText(rData.name);//w w  w. j a va2 s . c  o  m
    // Flag
    if (rData.flagURL != null) {
        imageLoader.displayImage(rData.flagURL, flag, options);
    } else {
        flag.setVisibility(View.GONE);
    }
    // WA Delegate
    StyleSpan bold = new StyleSpan(android.graphics.Typeface.BOLD);
    String wadTitle = getResources().getString(R.string.wad);
    String wad = TagParser.idToName(rData.delegate);
    if (!wad.equals("0")) {
        wad = wadTitle + ": <a href=\"com.limewoodMedia.nsdroid.nation://" + wad + "\">" + wad + "</a>";
        delegate.setText(Html.fromHtml(wad), TextView.BufferType.SPANNABLE);
    } else {
        delegate.setText(wadTitle + " " + getResources().getString(R.string.no_wad));
    }
    ((Spannable) delegate.getText()).setSpan(bold, 0, wadTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    // Founder
    String found = TagParser.idToName(rData.founder);
    if (!found.equals("0")) {
        String fTitle = getResources().getString(R.string.founder);
        found = fTitle + ": <a href=\"com.limewoodMedia.nsdroid.nation://" + found + "\">" + found + "</a>";
        founder.setText(Html.fromHtml(found), TextView.BufferType.SPANNABLE);
        ((Spannable) founder.getText()).setSpan(bold, 0, fTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        founder.setVisibility(View.VISIBLE);
    } else {
        founder.setVisibility(View.GONE);
    }
    text.setText(TagParser.parseTagsFromHtml(rData.factbook));
    layout.setVisibility(View.VISIBLE);

    doSearchSetup();
}