Example usage for android.text SpannableStringBuilder SpannableStringBuilder

List of usage examples for android.text SpannableStringBuilder SpannableStringBuilder

Introduction

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

Prototype

public SpannableStringBuilder(CharSequence text) 

Source Link

Document

Create a new SpannableStringBuilder containing a copy of the specified text, including its spans if any.

Usage

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.coreform.open.android.formidablevalidation.ValidationManager.java

public boolean validateAllAndSetError() {
    //validateAll
    HashMap<String, FinalValidationResult> finalValidationResultMap = validateAll(true);
    if (finalValidationResultMap.isEmpty()) {
        //all valid
        return true;
    } else {//  w w  w .j a va  2  s  . com
        //something invalid
        if (DEBUG)
            Log.d(TAG, "...at least one field is invalid, perhaps more.");
        if (DEBUG)
            Log.d(TAG, "...number of invalid fields: " + Integer.toString(finalValidationResultMap.size()));
        boolean setErrorAlreadyShown = false;
        View firstInvalidView = null;
        SpannableStringBuilder firstInvalidErrorText = null;
        validationLoop: for (Entry<String, FinalValidationResult> entry : finalValidationResultMap.entrySet()) {
            if (DEBUG)
                Log.d(TAG, "...validation result failed for field: " + entry.getKey());
            FinalValidationResult aFinalValidationResult = entry.getValue();
            boolean invalidDependencyTakesPrecedence = false;
            boolean invalidFieldHasAlreadyBeenFocused = false; //used to force focus to the first invalid field in List instead of last
            if (!aFinalValidationResult.isDependencyValid()) {
                if (DEBUG)
                    Log.d(TAG, "...dependency validation failed, with message: "
                            + aFinalValidationResult.getDependencyInvalidMessage());
                invalidDependencyTakesPrecedence = true;
                //if(DEBUG) Log.d(TAG, "aFinalValidationResult source's class: "+aFinalValidationResult.getSource().getClass().getSimpleName());
                if ("EditText".equals(aFinalValidationResult.getSource().getClass().getSimpleName())) {
                    if (!invalidFieldHasAlreadyBeenFocused) {
                        invalidFieldHasAlreadyBeenFocused = true;
                    }
                    //setError
                    SpannableStringBuilder errorText = new SpannableStringBuilder(
                            aFinalValidationResult.getDependencyInvalidMessage());
                    ((EditText) aFinalValidationResult.getSource()).setError(errorText);
                    setErrorAlreadyShown = true;
                    if (firstInvalidView == null) {
                        firstInvalidView = (View) aFinalValidationResult.getSource();
                        firstInvalidErrorText = errorText;
                    }
                }
            }
            if (!aFinalValidationResult.isValueValid()) {
                //note: ValueValidationResults for which careInvalid = false should NOT have caused a submission of FinalValidationResult to this List
                if (DEBUG)
                    Log.d(TAG, "...value validation failed, with message: "
                            + aFinalValidationResult.getValueInvalidMessage());
                //only display value invalid message if dependency(ies) satisfied for this field
                if (!invalidDependencyTakesPrecedence) {
                    if (aFinalValidationResult.getSource() == null) {
                        if (DEBUG)
                            Log.d(TAG, "...cannot display error balloon because source is null!");
                        //do nothing
                    } else if (aFinalValidationResult.getSource() instanceof SetErrorAble) {
                        //only set (don't show) error for a SetErrorAble View if no other Views have had their error set.
                        //...to avoid having multiple ErrorPopups displayed at same time (at least until User moves focus)
                        SpannableStringBuilder errorText = new SpannableStringBuilder(
                                aFinalValidationResult.getValueInvalidMessage());
                        if (DEBUG)
                            Log.d(TAG, "...set and show custom error balloon...");
                        if (true || !invalidFieldHasAlreadyBeenFocused) {
                            invalidFieldHasAlreadyBeenFocused = true;
                        }
                        //setError (for a button, this won't requestFocus() and won't show the message in a popup...it only sets the exclamation inner drawable)
                        ((SetErrorAble) aFinalValidationResult.getSource()).betterSetError(errorText, false);
                        setErrorAlreadyShown = true;
                        if (firstInvalidView == null) {
                            firstInvalidView = (View) aFinalValidationResult.getSource();
                            firstInvalidErrorText = errorText;
                        }
                    } else if (aFinalValidationResult.getSource() instanceof TextView) {
                        if (DEBUG)
                            Log.d(TAG, "...set and show native error balloon...");
                        if (!invalidFieldHasAlreadyBeenFocused) {
                            invalidFieldHasAlreadyBeenFocused = true;
                        }
                        //setError
                        SpannableStringBuilder errorText = new SpannableStringBuilder(
                                aFinalValidationResult.getValueInvalidMessage());
                        ((TextView) aFinalValidationResult.getSource()).setError(errorText);
                        setErrorAlreadyShown = true;
                        if (firstInvalidView == null) {
                            firstInvalidView = (View) aFinalValidationResult.getSource();
                            firstInvalidErrorText = errorText;
                        }
                    } else {
                        if (DEBUG)
                            Log.d(TAG, "...field does not support .setError()!");
                    }
                }
            }
        }
        //need to delay accessibility announcement so its the last View to steal focus
        if (DEBUG)
            Log.d(TAG, "firstInvalidErrorText: " + firstInvalidErrorText);
        AnnounceForAccessibilityRunnable announceForAccessibilityRunnable = new AnnounceForAccessibilityRunnable(
                firstInvalidErrorText);
        mHandler.postDelayed(announceForAccessibilityRunnable, ACCESSIBILITY_ANNOUNCE_DELAY);
        if (((View) firstInvalidView).isFocusable() && ((View) firstInvalidView).isFocusableInTouchMode()) {
            ((View) firstInvalidView).requestFocus();
        } else if (firstInvalidView instanceof SetErrorAble) {
            ((SetErrorAble) firstInvalidView).betterSetError(firstInvalidErrorText, true);
            ((View) firstInvalidView).requestFocusFromTouch(); //probably won't do much

        }
        return false;
    }
}

From source file:com.fa.mastodon.activity.MainActivity.java

private void setupSearchView() {
    searchView.attachNavigationDrawerToMenuButton(drawer.getDrawerLayout());

    // Setup content descriptions for the different elements in the search view.
    final View leftAction = searchView.findViewById(R.id.left_action);
    leftAction.setContentDescription(getString(R.string.action_open_drawer));
    searchView.setOnFocusChangeListener(new FloatingSearchView.OnFocusChangeListener() {
        @Override/*  w w  w .j av  a  2  s  . com*/
        public void onFocus() {
            leftAction.setContentDescription(getString(R.string.action_close));
        }

        @Override
        public void onFocusCleared() {
            leftAction.setContentDescription(getString(R.string.action_open_drawer));
        }
    });
    View clearButton = searchView.findViewById(R.id.clear_btn);
    clearButton.setContentDescription(getString(R.string.action_clear));

    searchView.setOnQueryChangeListener(new FloatingSearchView.OnQueryChangeListener() {
        @Override
        public void onSearchTextChanged(String oldQuery, String newQuery) {
            if (!oldQuery.equals("") && newQuery.equals("")) {
                searchView.clearSuggestions();
                return;
            }

            if (newQuery.length() < 3) {
                return;
            }

            searchView.showProgress();

            mastodonAPI.searchAccounts(newQuery, false, 5).enqueue(new Callback<List<Account>>() {
                @Override
                public void onResponse(Call<List<Account>> call, Response<List<Account>> response) {
                    if (response.isSuccessful()) {
                        searchView.swapSuggestions(response.body());
                        searchView.hideProgress();
                    } else {
                        searchView.hideProgress();
                    }
                }

                @Override
                public void onFailure(Call<List<Account>> call, Throwable t) {
                    searchView.hideProgress();
                }
            });
        }
    });

    searchView.setOnSearchListener(new FloatingSearchView.OnSearchListener() {
        @Override
        public void onSuggestionClicked(SearchSuggestion searchSuggestion) {
            Account accountSuggestion = (Account) searchSuggestion;
            Intent intent = new Intent(MainActivity.this, AccountActivity.class);
            intent.putExtra("id", accountSuggestion.id);
            startActivity(intent);
        }

        @Override
        public void onSearchAction(String currentQuery) {
        }
    });

    searchView.setOnBindSuggestionCallback(new SearchSuggestionsAdapter.OnBindSuggestionCallback() {
        @Override
        public void onBindSuggestion(View suggestionView, ImageView leftIcon, TextView textView,
                SearchSuggestion item, int itemPosition) {
            Account accountSuggestion = ((Account) item);

            Picasso.with(MainActivity.this).load(accountSuggestion.avatar)
                    .placeholder(R.drawable.avatar_default).into(leftIcon);

            String searchStr = accountSuggestion.getDisplayName() + " " + accountSuggestion.username;
            final SpannableStringBuilder str = new SpannableStringBuilder(searchStr);

            str.setSpan(new StyleSpan(Typeface.BOLD), 0, accountSuggestion.getDisplayName().length(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            textView.setText(str);
            textView.setMaxLines(1);
            textView.setEllipsize(TextUtils.TruncateAt.END);
        }
    });

    if (PreferenceManager.getDefaultSharedPreferences(this).getString("theme_selection", "light")
            .equals("black")) {
        searchView.setBackgroundColor(Color.parseColor("#444444"));
    }

}

From source file:com.forrestguice.suntimeswidget.SuntimesUtils.java

public static SpannableStringBuilder createSpan(Context context, String text, ImageSpanTag[] tags) {
    SpannableStringBuilder span = new SpannableStringBuilder(text);
    ImageSpan blank = createImageSpan(context, R.drawable.ic_transparent, 0, 0, R.color.transparent);

    for (ImageSpanTag tag : tags) {
        String spanTag = tag.getTag();
        ImageSpan imageSpan = (tag.getSpan() == null) ? blank : tag.getSpan();

        int tagPos;
        while ((tagPos = text.indexOf(spanTag)) >= 0) {
            int tagEnd = tagPos + spanTag.length();
            //Log.d("DEBUG", "tag=" + spanTag + ", tagPos=" + tagPos + ", " + tagEnd + ", text=" + text);

            span.setSpan(createImageSpan(imageSpan), tagPos, tagEnd, ImageSpan.ALIGN_BASELINE);
            text = text.substring(0, tagPos) + tag.getBlank() + text.substring(tagEnd);
        }//from   ww w  . j a v  a2s  . c  om
    }
    return span;
}

From source file:org.matrix.console.fragments.ConsoleMessageListFragment.java

public void onReadReceiptClick(String eventId, String userId, ReceiptData receipt) {
    RoomMember member = mRoom.getMember(userId);

    // sanity check
    if (null != member) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

        SpannableStringBuilder body = new SpannableStringBuilder(getActivity().getString(R.string.read_receipt)
                + " : " + dateFormat.format(new Date(receipt.originServerTs)));
        body.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD), 0,
                getActivity().getString(R.string.read_receipt).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        new AlertDialog.Builder(ConsoleApplication.getCurrentActivity()).setTitle(member.getName())
                .setMessage(body).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override//from  w  w w. j  a  va2s . co m
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create().show();
    }
}

From source file:com.heath_bar.tvdb.SeriesOverview.java

/** Update the GUI with the specified rating */
private void setUserRatingTextView(int rating) {

    try {//from w  w  w  .  j  a va2s  . com
        TextView ratingTextView = (TextView) findViewById(R.id.rating);
        String communityRating = (seriesInfo == null) ? "?" : seriesInfo.getRating();
        String communityRatingText = communityRating + " / 10";

        String ratingTextA = communityRatingText + "  (";
        String ratingTextB = (rating == 0) ? "rate" : String.valueOf(rating);
        String ratingTextC = ")";

        int start = ratingTextA.length();
        int end = ratingTextA.length() + ratingTextB.length();

        SpannableStringBuilder ssb = new SpannableStringBuilder(ratingTextA + ratingTextB + ratingTextC);

        ssb.setSpan(new NonUnderlinedClickableSpan() {
            @Override
            public void onClick(View v) {
                showRatingDialog();
            }
        }, start, end, 0);

        ssb.setSpan(new TextAppearanceSpan(getApplicationContext(), R.style.episode_link), start, end, 0); // Set the style of the text
        ratingTextView.setText(ssb, BufferType.SPANNABLE);
        ratingTextView.setMovementMethod(LinkMovementMethod.getInstance());
    } catch (Exception e) {
        Log.e("SeriesOverview", "Failed to setUserRatingTextView: " + e.getMessage());
    }
}

From source file:com.sina.weibo.sdk.demo.sample.activity.TestFragment.java

public SpannableStringBuilder setTextColor(String str) {
    // ????????/*from w w w  .  ja  va2 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:com.android.tv.dvr.ui.DvrUiHelper.java

@NonNull
public static CharSequence getStyledTitleWithEpisodeNumber(Context context, String title, String seasonNumber,
        String episodeNumber, int episodeNumberStyleResId) {
    if (TextUtils.isEmpty(title)) {
        return "";
    }/*from  w  ww .  ja v a  2 s  .  c  o m*/
    SpannableStringBuilder builder;
    if (TextUtils.isEmpty(seasonNumber) || seasonNumber.equals("0")) {
        builder = TextUtils.isEmpty(episodeNumber) ? new SpannableStringBuilder(title)
                : new SpannableStringBuilder(Html.fromHtml(context.getString(
                        R.string.program_title_with_episode_number_no_season, title, episodeNumber)));
    } else {
        builder = new SpannableStringBuilder(Html.fromHtml(context
                .getString(R.string.program_title_with_episode_number, title, seasonNumber, episodeNumber)));
    }
    Object[] spans = builder.getSpans(0, builder.length(), Object.class);
    if (spans.length > 0) {
        if (episodeNumberStyleResId != 0) {
            builder.setSpan(new TextAppearanceSpan(context, episodeNumberStyleResId),
                    builder.getSpanStart(spans[0]), builder.getSpanEnd(spans[0]),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        builder.removeSpan(spans[0]);
    }
    return new SpannableString(builder);
}

From source file:io.plaidapp.ui.HomeActivity.java

private void setNoFiltersEmptyTextVisibility(int visibility) {
    if (visibility == View.VISIBLE) {
        if (noFiltersEmptyText == null) {
            // create the no filters empty text
            ViewStub stub = (ViewStub) findViewById(R.id.stub_no_filters);
            noFiltersEmptyText = (TextView) stub.inflate();
            String emptyText = getString(R.string.no_filters_selected);
            int filterPlaceholderStart = emptyText.indexOf('\u08B4');
            int altMethodStart = filterPlaceholderStart + 3;
            SpannableStringBuilder ssb = new SpannableStringBuilder(emptyText);
            // show an image of the filter icon
            ssb.setSpan(new ImageSpan(this, R.drawable.ic_filter_small, ImageSpan.ALIGN_BASELINE),
                    filterPlaceholderStart, filterPlaceholderStart + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            // make the alt method (swipe from right) less prominent and italic
            ssb.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.text_secondary_light)),
                    altMethodStart, emptyText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            ssb.setSpan(new StyleSpan(Typeface.ITALIC), altMethodStart, emptyText.length(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            noFiltersEmptyText.setText(ssb);
            noFiltersEmptyText.setOnClickListener(new View.OnClickListener() {
                @Override/*from   w  w  w . j a  va 2  s .  c  om*/
                public void onClick(View v) {
                    drawer.openDrawer(GravityCompat.END);
                }
            });
        }
        noFiltersEmptyText.setVisibility(visibility);
    } else if (noFiltersEmptyText != null) {
        noFiltersEmptyText.setVisibility(visibility);
    }

}

From source file:android_network.hetnet.vpn_service.AdapterRule.java

private void markPro(MenuItem menu, String sku) {
    if (true) {/* w ww . j  a  v a 2  s.c o  m*/
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        boolean dark = prefs.getBoolean("dark_theme", false);
        SpannableStringBuilder ssb = new SpannableStringBuilder("  " + menu.getTitle());
        ssb.setSpan(
                new ImageSpan(context,
                        dark ? R.drawable.ic_shopping_cart_white_24dp : R.drawable.ic_shopping_cart_black_24dp),
                0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        menu.setTitle(ssb);
    }
}