Example usage for android.text SpannableString valueOf

List of usage examples for android.text SpannableString valueOf

Introduction

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

Prototype

public static SpannableString valueOf(CharSequence source) 

Source Link

Usage

From source file:org.mariotaku.twidere.util.StatusActionModeCallback.java

@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
    final int start = textView.getSelectionStart(), end = textView.getSelectionEnd();
    final SpannableString string = SpannableString.valueOf(textView.getText());
    final URLSpan[] spans = string.getSpans(start, end, URLSpan.class);
    final boolean avail = spans.length == 1 && URLUtil.isValidUrl(spans[0].getURL());
    MenuUtils.setMenuItemAvailability(menu, android.R.id.copyUrl, avail);
    MenuUtils.setMenuItemShowAsActionFlags(menu, android.R.id.copyUrl, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
    return true;//from ww  w . j  a v a2  s  . co m
}

From source file:org.mariotaku.twidere.util.StatusActionModeCallback.java

@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.copyUrl: {
        final int start = textView.getSelectionStart(), end = textView.getSelectionEnd();
        final SpannableString string = SpannableString.valueOf(textView.getText());
        final URLSpan[] spans = string.getSpans(start, end, URLSpan.class);
        if (spans.length != 1)
            return true;
        ClipboardUtils.setText(context, spans[0].getURL());
        mode.finish();/*from w  w w .j ava 2  s . co m*/
        return true;
    }
    }
    return false;
}

From source file:com.qiscus.sdk.ui.adapter.viewholder.QiscusBaseLinkViewHolder.java

private void clickify(String clickableText, ClickSpan.OnClickListener listener) {
    CharSequence text = messageTextView.getText();
    String string = text.toString();
    ClickSpan span = new ClickSpan(listener);

    int start = string.indexOf(clickableText);
    int end = start + clickableText.length();
    if (start == -1) {
        return;//from   w  w w  . j a v  a 2s.  co  m
    }

    if (text instanceof Spannable) {
        ((Spannable) text).setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    } else {
        SpannableString s = SpannableString.valueOf(text);
        s.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        messageTextView.setText(s);
    }

    MovementMethod m = messageTextView.getMovementMethod();
    if (m == null || !(m instanceof LinkMovementMethod)) {
        messageTextView.setMovementMethod(LinkMovementMethod.getInstance());
    }
}

From source file:com.ntsync.android.sync.activities.KeyPasswordActivity.java

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    SystemHelper.initSystem(this);

    Log.i(TAG, "loading data from Intent");
    final Intent intent = getIntent();
    mUsername = intent.getStringExtra(PARAM_USERNAME);
    pwdSalt = intent.getByteArrayExtra(PARAM_SALT);
    pwdCheck = intent.getByteArrayExtra(PARAM_CHECK);

    requestWindowFeature(Window.FEATURE_LEFT_ICON);
    setContentView(R.layout.keypassword_activity);
    getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.key);
    mMessage = (TextView) findViewById(R.id.message_bottom);

    mPasswordEdit = new AutoCompleteTextView[5];
    mPasswordEdit[0] = (AutoCompleteTextView) findViewById(R.id.pwd1_edit);
    mPasswordEdit[1] = (AutoCompleteTextView) findViewById(R.id.pwd2_edit);
    mPasswordEdit[2] = (AutoCompleteTextView) findViewById(R.id.pwd3_edit);
    mPasswordEdit[3] = (AutoCompleteTextView) findViewById(R.id.pwd4_edit);
    mPasswordEdit[4] = (AutoCompleteTextView) findViewById(R.id.pwd5_edit);
    for (AutoCompleteTextView textView : mPasswordEdit) {
        textView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE
                | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_VARIATION_PASSWORD);
    }/*from w w w.j a va2 s . co m*/

    if (pwdSalt == null || pwdSalt.length != ClientKeyHelper.SALT_LENGHT || pwdCheck == null) {
        // disable password input
        for (AutoCompleteTextView textView : mPasswordEdit) {
            if (textView != null) {
                textView.setEnabled(false);
            }
        }
    }
    msgNewKey = (TextView) findViewById(R.id.message_newkey);
    SpannableString newKeyText = SpannableString.valueOf(getText(R.string.keypwd_activity_newkey_label));

    newKeyText.setSpan(new InternalURLSpan(this), 0, newKeyText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    msgNewKey.setText(newKeyText, BufferType.SPANNABLE);
    msgNewKey.setMovementMethod(LinkMovementMethod.getInstance());
}

From source file:org.chromium.chrome.browser.omnibox.SuggestionView.java

/**
 * Sets the contents and state of the view for the given suggestion.
 *
 * @param suggestionItem The omnibox suggestion item this view represents.
 * @param suggestionDelegate The suggestion delegate.
 * @param position Position of the suggestion in the dropdown list.
 * @param useDarkColors Whether dark colors should be used for fonts and icons.
 */// w  ww. j a va2  s  .  co m
public void init(OmniboxResultItem suggestionItem, OmniboxSuggestionDelegate suggestionDelegate, int position,
        boolean useDarkColors) {
    ViewCompat.setLayoutDirection(this, ViewCompat.getLayoutDirection(mUrlBar));

    // Update the position unconditionally.
    mPosition = position;
    jumpDrawablesToCurrentState();
    boolean colorsChanged = mUseDarkColors == null || mUseDarkColors != useDarkColors;
    if (suggestionItem.equals(mSuggestionItem) && !colorsChanged)
        return;
    mUseDarkColors = useDarkColors;
    if (colorsChanged) {
        mContentsView.mTextLine1.setTextColor(getStandardFontColor());
        setRefineIcon(true);
    }

    mSuggestionItem = suggestionItem;
    mSuggestion = suggestionItem.getSuggestion();
    mSuggestionDelegate = suggestionDelegate;
    // Reset old computations.
    mContentsView.resetTextWidths();
    mContentsView.mAnswerImage.setVisibility(GONE);
    mContentsView.mAnswerImage.getLayoutParams().height = 0;
    mContentsView.mAnswerImage.getLayoutParams().width = 0;
    mContentsView.mAnswerImage.setImageDrawable(null);
    mContentsView.mAnswerImageMaxSize = 0;
    mContentsView.mTextLine1.setTextSize(TypedValue.COMPLEX_UNIT_PX,
            getResources().getDimension(R.dimen.omnibox_suggestion_first_line_text_size));
    mContentsView.mTextLine2.setTextSize(TypedValue.COMPLEX_UNIT_PX,
            getResources().getDimension(R.dimen.omnibox_suggestion_second_line_text_size));

    // Suggestions with attached answers are rendered with rich results regardless of which
    // suggestion type they are.
    if (mSuggestion.hasAnswer()) {
        setAnswer(mSuggestion.getAnswer());
        mContentsView.setSuggestionIcon(SUGGESTION_ICON_MAGNIFIER, colorsChanged);
        mContentsView.mTextLine2.setVisibility(VISIBLE);
        setRefinable(true);
        return;
    } else {
        mNumAnswerLines = 1;
        mContentsView.mTextLine2.setEllipsize(null);
        mContentsView.mTextLine2.setSingleLine();
    }

    boolean sameAsTyped = suggestionItem.getMatchedQuery().equalsIgnoreCase(mSuggestion.getDisplayText());
    int suggestionType = mSuggestion.getType();
    if (mSuggestion.isUrlSuggestion()) {
        if (mSuggestion.isStarred()) {
            mContentsView.setSuggestionIcon(SUGGESTION_ICON_BOOKMARK, colorsChanged);
        } else if (suggestionType == OmniboxSuggestionType.HISTORY_URL) {
            mContentsView.setSuggestionIcon(SUGGESTION_ICON_HISTORY, colorsChanged);
        } else {
            mContentsView.setSuggestionIcon(SUGGESTION_ICON_GLOBE, colorsChanged);
        }
        boolean urlShown = !TextUtils.isEmpty(mSuggestion.getUrl());
        boolean urlHighlighted = false;
        if (urlShown) {
            urlHighlighted = setUrlText(suggestionItem);
        } else {
            mContentsView.mTextLine2.setVisibility(INVISIBLE);
        }
        setSuggestedQuery(suggestionItem, true, urlShown, urlHighlighted);
        setRefinable(!sameAsTyped);
    } else {
        @SuggestionIcon
        int suggestionIcon = SUGGESTION_ICON_MAGNIFIER;
        if (suggestionType == OmniboxSuggestionType.VOICE_SUGGEST) {
            suggestionIcon = SUGGESTION_ICON_VOICE;
        } else if ((suggestionType == OmniboxSuggestionType.SEARCH_SUGGEST_PERSONALIZED)
                || (suggestionType == OmniboxSuggestionType.SEARCH_HISTORY)) {
            // Show history icon for suggestions based on user queries.
            suggestionIcon = SUGGESTION_ICON_HISTORY;
        }
        mContentsView.setSuggestionIcon(suggestionIcon, colorsChanged);
        setRefinable(!sameAsTyped);
        setSuggestedQuery(suggestionItem, false, false, false);
        if ((suggestionType == OmniboxSuggestionType.SEARCH_SUGGEST_ENTITY)
                || (suggestionType == OmniboxSuggestionType.SEARCH_SUGGEST_PROFILE)) {
            showDescriptionLine(SpannableString.valueOf(mSuggestion.getDescription()), false);
        } else {
            mContentsView.mTextLine2.setVisibility(INVISIBLE);
        }
    }
}

From source file:org.chromium.chrome.browser.omnibox.SuggestionView.java

/**
 * Sets (and highlights) the URL text of the second line of the omnibox suggestion.
 *
 * @param result The suggestion containing the URL.
 * @return Whether the URL was highlighted based on the user query.
 *//*from   w w w.  ja va2  s  .  com*/
private boolean setUrlText(OmniboxResultItem result) {
    OmniboxSuggestion suggestion = result.getSuggestion();
    Spannable str = SpannableString.valueOf(suggestion.getDisplayText());
    boolean hasMatch = applyHighlightToMatchRegions(str, suggestion.getDisplayTextClassifications());
    showDescriptionLine(str, true);
    return hasMatch;
}

From source file:de.vanita5.twittnuker.fragment.support.StatusFragment.java

@Override
public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.copyUrl: {
        final int start = mTextView.getSelectionStart(), end = mTextView.getSelectionEnd();
        final SpannableString string = SpannableString.valueOf(mTextView.getText());
        final URLSpan[] spans = string.getSpans(start, end, URLSpan.class);
        if (spans == null || spans.length != 1)
            return true;
        ClipboardUtils.setText(getActivity(), spans[0].getURL());
        mode.finish();// w  w w  .  j  ava2  s.  c om
        return true;
    }
    }
    return false;
}

From source file:org.chromium.chrome.browser.omnibox.SuggestionView.java

/**
 * Sets the text of the first line of the omnibox suggestion.
 *
 * @param suggestionItem The item containing the suggestion data.
 * @param showDescriptionIfPresent Whether to show the description text of the suggestion if
 *                                 the item contains valid data.
 * @param isUrlQuery Whether this suggestion is showing an URL.
 * @param isUrlHighlighted Whether the URL contains any highlighted matching sections.
 *//* www  .  ja va2  s.  co m*/
private void setSuggestedQuery(OmniboxResultItem suggestionItem, boolean showDescriptionIfPresent,
        boolean isUrlQuery, boolean isUrlHighlighted) {
    String userQuery = suggestionItem.getMatchedQuery();
    String suggestedQuery = null;
    List<MatchClassification> classifications;
    OmniboxSuggestion suggestion = suggestionItem.getSuggestion();
    if (showDescriptionIfPresent && !TextUtils.isEmpty(suggestion.getUrl())
            && !TextUtils.isEmpty(suggestion.getDescription())) {
        suggestedQuery = suggestion.getDescription();
        classifications = suggestion.getDescriptionClassifications();
    } else {
        suggestedQuery = suggestion.getDisplayText();
        classifications = suggestion.getDisplayTextClassifications();
    }
    if (suggestedQuery == null) {
        assert false : "Invalid suggestion sent with no displayable text";
        suggestedQuery = "";
        classifications = new ArrayList<MatchClassification>();
        classifications.add(new MatchClassification(0, MatchClassificationStyle.NONE));
    }

    if (mSuggestion.getType() == OmniboxSuggestionType.SEARCH_SUGGEST_TAIL) {
        String fillIntoEdit = mSuggestion.getFillIntoEdit();
        // Data sanity checks.
        if (fillIntoEdit.startsWith(userQuery) && fillIntoEdit.endsWith(suggestedQuery)
                && fillIntoEdit.length() < userQuery.length() + suggestedQuery.length()) {
            final String ellipsisPrefix = "\u2026 ";
            suggestedQuery = ellipsisPrefix + suggestedQuery;

            // Offset the match classifications by the length of the ellipsis prefix to ensure
            // the highlighting remains correct.
            for (int i = 0; i < classifications.size(); i++) {
                classifications.set(i, new MatchClassification(
                        classifications.get(i).offset + ellipsisPrefix.length(), classifications.get(i).style));
            }
            classifications.add(0, new MatchClassification(0, MatchClassificationStyle.NONE));

            if (DeviceFormFactor.isTablet(getContext())) {
                TextPaint tp = mContentsView.mTextLine1.getPaint();
                mContentsView.mRequiredWidth = tp.measureText(fillIntoEdit, 0, fillIntoEdit.length());
                mContentsView.mMatchContentsWidth = tp.measureText(suggestedQuery, 0, suggestedQuery.length());

                // Update the max text widths values in SuggestionList. These will be passed to
                // the contents view on layout.
                mSuggestionDelegate.onTextWidthsUpdated(mContentsView.mRequiredWidth,
                        mContentsView.mMatchContentsWidth);
            }
        }
    }

    Spannable str = SpannableString.valueOf(suggestedQuery);
    if (!isUrlHighlighted)
        applyHighlightToMatchRegions(str, classifications);
    mContentsView.mTextLine1.setText(str, BufferType.SPANNABLE);
}

From source file:de.vanita5.twittnuker.fragment.support.StatusFragment.java

@Override
public boolean onPrepareActionMode(final ActionMode mode, final Menu menu) {
    final int start = mTextView.getSelectionStart(), end = mTextView.getSelectionEnd();
    final SpannableString string = SpannableString.valueOf(mTextView.getText());
    final URLSpan[] spans = string.getSpans(start, end, URLSpan.class);
    final boolean avail = spans != null && spans.length == 1 && URLUtil.isValidUrl(spans[0].getURL());
    Utils.setMenuItemAvailability(menu, android.R.id.copyUrl, avail);
    return false;
}

From source file:com.atwal.wakeup.battery.util.Utilities.java

public static SpannableString highlightKeywords(int color, String text, String keywords,
        boolean actionFirstMatch) {

    if (text != null && keywords != null && text.trim().length() == keywords.trim().length()) {
        return SpannableString.valueOf(text.trim());
    }//from w w  w .  j a  v  a 2s.  c o m

    SpannableString s = new SpannableString(text);
    Pattern p = Pattern.compile(keywords, Pattern.LITERAL);
    Matcher m = p.matcher(s);
    while (m.find()) {
        int end = m.end();
        try {
            if (s.charAt(end) != ' ') {
                s.setSpan(new UnderlineSpan(), end, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else {
                s.setSpan(new UnderlineSpan(), end + 1, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (actionFirstMatch) {
            break;
        }
    }
    return s;
}