Example usage for android.text.style URLSpan URLSpan

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

Introduction

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

Prototype

public URLSpan(@NonNull Parcel src) 

Source Link

Document

Constructs a URLSpan from a parcel.

Usage

From source file:com.google.zxing.client.android.result.supplement.SupplementalInfoRetriever.java

final void append(String itemID, String source, String[] newTexts, String linkURL) throws InterruptedException {

    final TextView textView = textViewRef.get();
    if (textView == null) {
        throw new InterruptedException();
    }//w ww  .ja va  2 s. c om

    StringBuilder newTextCombined = new StringBuilder();

    if (source != null) {
        newTextCombined.append(source).append(" : ");
    }

    int linkStart = newTextCombined.length();

    boolean first = true;
    for (String newText : newTexts) {
        if (first) {
            newTextCombined.append(newText);
            first = false;
        } else {
            newTextCombined.append(" [");
            newTextCombined.append(newText);
            newTextCombined.append(']');
        }
    }

    int linkEnd = newTextCombined.length();

    String newText = newTextCombined.toString();
    final Spannable content = new SpannableString(newText + "\n\n");
    if (linkURL != null) {
        content.setSpan(new URLSpan(linkURL), linkStart, linkEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    handler.post(new Runnable() {
        public void run() {
            textView.append(content);
            textView.setMovementMethod(LinkMovementMethod.getInstance());
        }
    });

    // Add the text to the history.
    historyManager.addHistoryItemDetails(itemID, newText);
}

From source file:com.joyepay.qrcode.result.supplement.SupplementalInfoRetriever.java

final void append(String itemID, String source, String[] newTexts, String linkURL) throws InterruptedException {

    final TextView textView = textViewRef.get();
    if (textView == null) {
        throw new InterruptedException();
    }/*www .j  av a  2 s. c  o m*/

    StringBuilder newTextCombined = new StringBuilder();

    if (source != null) {
        newTextCombined.append(source).append(" : ");
    }

    int linkStart = newTextCombined.length();

    boolean first = true;
    for (String newText : newTexts) {
        if (first) {
            newTextCombined.append(newText);
            first = false;
        } else {
            newTextCombined.append(" [");
            newTextCombined.append(newText);
            newTextCombined.append(']');
        }
    }

    int linkEnd = newTextCombined.length();

    String newText = newTextCombined.toString();
    final Spannable content = new SpannableString(newText + "\n\n");
    if (linkURL != null) {
        content.setSpan(new URLSpan(linkURL), linkStart, linkEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    handler.post(new Runnable() {
        public void run() {
            textView.append(content);
            textView.setMovementMethod(LinkMovementMethod.getInstance());
        }
    });

    // Add the text to the history.
    //    historyManager.addHistoryItemDetails(itemID, newText);
}

From source file:io.github.marktony.espresso.mvp.companydetails.CompanyDetailFragment.java

@Override
public void setCompanyTel(String tel) {
    this.tel = tel;
    String companyTel = getString(R.string.phone_number) + "\n" + tel;
    Spannable spannable = new SpannableStringBuilder(companyTel);
    spannable.setSpan(new StyleSpan(Typeface.BOLD), 0, companyTel.length() - tel.length() - 1,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannable.setSpan(new URLSpan(tel), companyTel.length() - tel.length(), companyTel.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    textViewTel.setText(spannable);//  w w w . ja va2  s. c  o m
}

From source file:io.github.marktony.espresso.mvp.companydetails.CompanyDetailFragment.java

@Override
public void setCompanyWebsite(String website) {
    this.website = website;
    String ws = getString(R.string.official_website) + "\n" + website;
    Spannable spannable = new SpannableStringBuilder(ws);
    spannable.setSpan(new StyleSpan(Typeface.BOLD), 0, ws.length() - website.length() - 1,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannable.setSpan(new URLSpan(website), ws.length() - website.length(), ws.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    textViewWebsite.setText(spannable);//w  w w .  j av  a2  s.co m
}

From source file:cn.wjh1119.bestnews.ui.fragment.DetailFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (data != null && data.moveToFirst()) {

        //?????view
        FetchDetailDataFromSqlTask fetchDetailDataFromSqlTask = new FetchDetailDataFromSqlTask();
        fetchDetailDataFromSqlTask/*from  w w w .j a va2 s .  co  m*/
                .setOnDataFinishedListener(new FetchDetailDataFromSqlTask.OnDataFinishedListener() {
                    @Override
                    public void onDataSuccessfully(HashMap data) {

                        String title = data.get("title").toString();
                        String source = data.get("source").toString();
                        String pubDate = data.get("pubDate").toString();
                        String content = data.get("content").toString();
                        String link = data.get("link").toString();
                        //                    BitmapDrawable drawable = (BitmapDrawable) data.get("drawable");
                        Object imageTextFromSql = data.get("imageUrl");
                        String imageUrl = null;
                        if (imageTextFromSql != null) {
                            imageUrl = data.get("imageUrl").toString();
                        }

                        mTitleView.setText(title);
                        mTitleView.setFocusable(true);
                        mTitleView.setFocusableInTouchMode(true);
                        mTitleView.requestFocus();
                        TextPaint paint = mTitleView.getPaint();
                        paint.setFakeBoldText(true);
                        mSourceView.setText(source);
                        mPubDateView.setText(pubDate);
                        mContentView.setText(content);

                        if (imageUrl != null) {
                            Bitmap bitmap = imageManager.showCacheBitmap(imageUrl);
                            if (bitmap != null) {
                                mImageView.setImageBitmap(bitmap);

                            } else {
                                imageManager.downloadImage(imageUrl, new ImageManager.onImageLoaderListener() {

                                    @Override
                                    public void onImageLoader(Bitmap bitmap, String url) {
                                        if (bitmap != null) {
                                            mImageView.setImageBitmap(bitmap);
                                        } else {
                                            mImageView.setImageResource(R.mipmap.picture_fail_loading);
                                        }
                                    }
                                });
                            }
                        }

                        SpannableStringBuilder ssb = new SpannableStringBuilder("??");
                        ssb.setSpan(new URLSpan(link), 0, ssb.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

                        ForegroundColorSpan span = new ForegroundColorSpan(Color.BLUE);
                        ssb.setSpan(span, 0, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                        mLinkView.setText(ssb);
                        // ??MovementMethod
                        mLinkView.setMovementMethod(LinkMovementMethod.getInstance());
                        // ??ClickableSpan
                        mLinkView.setHighlightColor(0xff8FABCC);
                    }

                    @Override
                    public void onDataFailed() {

                    }
                });
        fetchDetailDataFromSqlTask.execute(data);
    }
    AppCompatActivity activity = (AppCompatActivity) getActivity();
    Toolbar toolbarView = (Toolbar) getView().findViewById(R.id.toolbar_detail);

    // We need to start the enter transition after the data has loaded
    if (mTransitionAnimation) {
        activity.supportStartPostponedEnterTransition();

        if (null != toolbarView) {
            activity.setSupportActionBar(toolbarView);
            activity.getSupportActionBar().setDisplayShowTitleEnabled(false);
            activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    } else {
        if (null != toolbarView) {
            Menu menu = toolbarView.getMenu();
            if (null != menu)
                menu.clear();
        }
    }
}

From source file:com.juick.android.TagsFragment.java

private void reloadTags(final View view) {
    final View selectedContainer = myView.findViewById(R.id.selected_container);
    final View progressAll = myView.findViewById(R.id.progress_all);
    Thread thr = new Thread(new Runnable() {

        public void run() {
            Bundle args = getArguments();
            MicroBlog microBlog;/* w  w w  .j a v  a 2 s  .c  o m*/
            JSONArray json = null;
            final int tagsUID = showMine ? uid : 0;
            if (PointMessageID.CODE.equals(args.getString("microblog"))) {
                microBlog = MainActivity.microBlogs.get(PointMessageID.CODE);
                json = ((PointMicroBlog) microBlog).getUserTags(view, uidS);
            } else {
                microBlog = MainActivity.microBlogs.get(JuickMessageID.CODE);
                json = ((JuickMicroBlog) microBlog).getUserTags(view, tagsUID);
            }
            if (isAdded()) {
                final SpannableStringBuilder tagsSSB = new SpannableStringBuilder();
                if (json != null) {
                    try {
                        int cnt = json.length();
                        ArrayList<TagSort> sortables = new ArrayList<TagSort>();
                        for (int i = 0; i < cnt; i++) {
                            final String tagg = json.getJSONObject(i).getString("tag");
                            final int messages = json.getJSONObject(i).getInt("messages");
                            sortables.add(new TagSort(tagg, messages));
                        }
                        Collections.sort(sortables);
                        HashMap<String, Double> scales = new HashMap<String, Double>();
                        for (int sz = 0, sortablesSize = sortables.size(); sz < sortablesSize; sz++) {
                            TagSort sortable = sortables.get(sz);
                            if (sz < 10) {
                                scales.put(sortable.tag, 2.0);
                            } else if (sz < 20) {
                                scales.put(sortable.tag, 1.5);
                            }
                        }
                        int start = 0;
                        if (microBlog instanceof JuickMicroBlog
                                && getArguments().containsKey("add_system_tags")) {
                            start = -4;
                        }
                        for (int i = start; i < cnt; i++) {
                            final String tagg;
                            switch (i) {
                            case -4:
                                tagg = "public";
                                break;
                            case -3:
                                tagg = "friends";
                                break;
                            case -2:
                                tagg = "notwitter";
                                break;
                            case -1:
                                tagg = "readonly";
                                break;
                            default:
                                tagg = json.getJSONObject(i).getString("tag");
                                break;

                            }
                            int index = tagsSSB.length();
                            tagsSSB.append("*" + tagg);
                            tagsSSB.setSpan(new URLSpan(tagg) {
                                @Override
                                public void onClick(View widget) {
                                    onTagClick(tagg, tagsUID);
                                }
                            }, index, tagsSSB.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            Double scale = scales.get(tagg);
                            if (scale != null) {
                                tagsSSB.setSpan(new RelativeSizeSpan((float) scale.doubleValue()), index,
                                        tagsSSB.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            }
                            tagOffsets.put(tagg, new TagOffsets(index, tagsSSB.length()));
                            tagsSSB.append(" ");

                        }
                    } catch (Exception ex) {
                        tagsSSB.append("Error: " + ex.toString());
                    }
                }
                if (getActivity() != null) {
                    // maybe already closed?
                    getActivity().runOnUiThread(new Runnable() {

                        public void run() {
                            TextView tv = (TextView) myView.findViewById(R.id.tags);
                            progressAll.setVisibility(View.GONE);
                            if (multi)
                                selectedContainer.setVisibility(View.VISIBLE);
                            tv.setText(tagsSSB, TextView.BufferType.SPANNABLE);
                            tv.setMovementMethod(LinkMovementMethod.getInstance());
                            MainActivity.restyleChildrenOrWidget(view);
                            final TextView selected = (TextView) myView.findViewById(R.id.selected);
                            selected.setVisibility(View.VISIBLE);
                        }
                    });
                }
            }
        }
    });
    thr.start();
}

From source file:com.nextgis.maplibui.util.ControlHelper.java

public static void highlightText(TextView textView) {
    final CharSequence text = textView.getText();
    final SpannableString spannableString = new SpannableString(text);
    spannableString.setSpan(new URLSpan(""), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setText(spannableString, TextView.BufferType.SPANNABLE);
}

From source file:org.tlhInganHol.android.klingonassistant.EntryActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // TTS:/*w  w w.  jav a2 s.c o m*/
    // Initialize text-to-speech. This is an asynchronous operation.
    // The OnInitListener (second argument) is called after initialization completes.
    // Log.d(TAG, "Initialising TTS");
    mTts = new TextToSpeech(this, this, // TextToSpeech.OnInitListener
            "org.tlhInganHol.android.klingonttsengine"); // Requires API 14.

    setDrawerContentView(R.layout.entry);
    Resources resources = getResources();

    JellyBeanSpanFixTextView entryTitle = (JellyBeanSpanFixTextView) findViewById(R.id.entry_title);
    JellyBeanSpanFixTextView entryText = (JellyBeanSpanFixTextView) findViewById(R.id.definition);

    // TODO: Save and restore bundle state to preserve links.

    Uri uri = getIntent().getData();
    // Log.d(TAG, "EntryActivity - uri: " + uri.toString());
    // TODO: Disable the "About" menu item if this is the "About" entry.
    mParentQuery = getIntent().getStringExtra(SearchManager.QUERY);

    // Retrieve the entry's data.
    // Note: managedQuery is deprecated since API 11.
    Cursor cursor = managedQuery(uri, KlingonContentDatabase.ALL_KEYS, null, null, null);
    KlingonContentProvider.Entry entry = new KlingonContentProvider.Entry(cursor, getBaseContext());

    // Handle alternative spellings here.
    if (entry.isAlternativeSpelling()) {
        // TODO: Immediate redirect to query in entry.getDefinition();
    }

    // Get the shared preferences.
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    // Set the entry's name (along with info like "slang", formatted in HTML).
    entryTitle.invalidate();
    boolean useKlingonFont = sharedPrefs.getBoolean(Preferences.KEY_KLINGON_FONT_CHECKBOX_PREFERENCE,
            /* default */false);
    Typeface klingonTypeface = KlingonAssistant.getKlingonFontTypeface(getBaseContext());
    if (useKlingonFont) {
        // Preference is set to display this in {pIqaD}!
        entryTitle.setTypeface(klingonTypeface);
        entryTitle.setText(entry.getEntryNameInKlingonFont());
    } else {
        // Boring transcription based on English (Latin) alphabet.
        entryTitle.setText(Html.fromHtml(entry.getFormattedEntryName(/* isHtml */true)));
    }
    mEntryName = entry.getEntryName();

    // Set the colour for the entry name depending on its part of speech.
    boolean useColours = sharedPrefs.getBoolean(Preferences.KEY_USE_COLOURS_CHECKBOX_PREFERENCE,
            /* default */true);
    if (useColours) {
        entryTitle.setTextColor(entry.getTextColor());
    }

    // Create the expanded definition.
    String pos = entry.getFormattedPartOfSpeech(/* isHtml */false);
    String expandedDefinition = pos + entry.getDefinition();

    // Show the German definition.
    String definition_DE = "";
    boolean displayGermanEntry = entry.shouldDisplayGerman();
    int germanDefinitionStart = -1;
    String germanDefinitionHeader = "\n" + resources.getString(R.string.label_german) + ": ";
    if (displayGermanEntry) {
        germanDefinitionStart = expandedDefinition.length();
        definition_DE = entry.getDefinition_DE();
        expandedDefinition += germanDefinitionHeader + definition_DE;
    }

    // Set the share intent.
    setShareEntryIntent(entry);

    // Show the basic notes.
    String notes = entry.getNotes();
    if (!notes.equals("")) {
        expandedDefinition += "\n\n" + notes;
    }

    // If this entry is hypothetical or extended canon, display warnings.
    if (entry.isHypothetical() || entry.isExtendedCanon()) {
        expandedDefinition += "\n\n";
        if (entry.isHypothetical()) {
            expandedDefinition += resources.getString(R.string.warning_hypothetical);
        }
        if (entry.isExtendedCanon()) {
            expandedDefinition += resources.getString(R.string.warning_extended_canon);
        }
    }

    // Show synonyms, antonyms, and related entries.
    String synonyms = entry.getSynonyms();
    String antonyms = entry.getAntonyms();
    String seeAlso = entry.getSeeAlso();
    if (!synonyms.equals("")) {
        expandedDefinition += "\n\n" + resources.getString(R.string.label_synonyms) + ": " + synonyms;
    }
    if (!antonyms.equals("")) {
        expandedDefinition += "\n\n" + resources.getString(R.string.label_antonyms) + ": " + antonyms;
    }
    if (!seeAlso.equals("")) {
        expandedDefinition += "\n\n" + resources.getString(R.string.label_see_also) + ": " + seeAlso;
    }

    // Display components if that field is not empty, unless we are showing an analysis link, in
    // which case we want to hide the components.
    boolean showAnalysis = entry.isSentence() || entry.isDerivative();
    String components = entry.getComponents();
    if (!components.equals("")) {
        // Treat the components column of inherent plurals and their
        // singulars differently than for other entries.
        if (entry.isInherentPlural()) {
            expandedDefinition += "\n\n"
                    + String.format(resources.getString(R.string.info_inherent_plural), components);
        } else if (entry.isSingularFormOfInherentPlural()) {
            expandedDefinition += "\n\n"
                    + String.format(resources.getString(R.string.info_singular_form), components);
        } else if (!showAnalysis) {
            // This is just a regular list of components.
            expandedDefinition += "\n\n" + resources.getString(R.string.label_components) + ": " + components;
        }
    }

    // Display plural information.
    if (!entry.isPlural() && !entry.isInherentPlural() && !entry.isPlural()) {
        if (entry.isBeingCapableOfLanguage()) {
            expandedDefinition += "\n\n" + resources.getString(R.string.info_being);
        } else if (entry.isBodyPart()) {
            expandedDefinition += "\n\n" + resources.getString(R.string.info_body);
        }
    }

    // If the entry is a useful phrase, link back to its category.
    if (entry.isSentence()) {
        String sentenceType = entry.getSentenceType();
        if (!sentenceType.equals("")) {
            // Put the query as a placeholder for the actual category.
            expandedDefinition += "\n\n" + resources.getString(R.string.label_category) + ": {"
                    + entry.getSentenceTypeQuery() + "}";
        }
    }

    // If the entry is a sentence, make a link to analyse its components.
    if (showAnalysis) {
        String analysisQuery = entry.getEntryName();
        if (!components.equals("")) {
            // Strip the brackets around each component so they won't be processed.
            analysisQuery += ":" + entry.getPartOfSpeech();
            int homophoneNumber = entry.getHomophoneNumber();
            if (homophoneNumber != -1) {
                analysisQuery += ":" + homophoneNumber;
            }
            analysisQuery += KlingonContentProvider.Entry.COMPONENTS_MARKER + components.replaceAll("[{}]", "");
        }
        expandedDefinition += "\n\n" + resources.getString(R.string.label_analyze) + ": {" + analysisQuery
                + "}";
    }

    // Show the examples.
    String examples = entry.getExamples();
    if (!examples.equals("")) {
        expandedDefinition += "\n\n" + resources.getString(R.string.label_examples) + ": " + examples;
    }

    // Show the source.
    String source = entry.getSource();
    if (!source.equals("")) {
        expandedDefinition += "\n\n" + resources.getString(R.string.label_sources) + ": " + source;
    }

    // If this is a verb (but not a prefix or suffix), show the transitivity information.
    String transitivity = "";
    if (entry.isVerb()
            && sharedPrefs.getBoolean(Preferences.KEY_SHOW_TRANSITIVITY_CHECKBOX_PREFERENCE, /* default */
                    true)) {
        // This is a verb and show transitivity preference is set to true.
        transitivity = entry.getTransitivityString();
    }
    int transitivityStart = -1;
    String transitivityHeader = "\n\n" + resources.getString(R.string.label_transitivity) + ": ";
    boolean showTransitivityInformation = !transitivity.equals("");
    if (showTransitivityInformation) {
        transitivityStart = expandedDefinition.length();
        expandedDefinition += transitivityHeader + transitivity;
    }

    // Show the hidden notes.
    String hiddenNotes = "";
    if (sharedPrefs.getBoolean(Preferences.KEY_SHOW_ADDITIONAL_INFORMATION_CHECKBOX_PREFERENCE, /* default */
            true)) {
        // Show additional information preference set to true.
        hiddenNotes = entry.getHiddenNotes();
    }
    int hiddenNotesStart = -1;
    String hiddenNotesHeader = "\n\n" + resources.getString(R.string.label_additional_information) + ": ";
    if (!hiddenNotes.equals("")) {
        hiddenNotesStart = expandedDefinition.length();
        expandedDefinition += hiddenNotesHeader + hiddenNotes;
    }

    // Format the expanded definition, including linkifying the links to other entries.
    float smallTextScale = (float) 0.8;
    SpannableStringBuilder ssb = new SpannableStringBuilder(expandedDefinition);
    int intermediateFlags = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_INTERMEDIATE;
    int finalFlags = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE;
    if (!pos.equals("")) {
        // Italicise the part of speech.
        ssb.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, pos.length(), finalFlags);
    }
    if (displayGermanEntry) {
        // Reduce the size of the German definition.
        ssb.setSpan(new RelativeSizeSpan(smallTextScale), germanDefinitionStart,
                germanDefinitionStart + germanDefinitionHeader.length() + definition_DE.length(), finalFlags);
    }
    if (showTransitivityInformation) {
        // Reduce the size of the transitivity information.
        ssb.setSpan(new RelativeSizeSpan(smallTextScale), transitivityStart,
                transitivityStart + transitivityHeader.length() + transitivity.length(), finalFlags);
    }
    if (!hiddenNotes.equals("")) {
        // Reduce the size of the hidden notes.
        ssb.setSpan(new RelativeSizeSpan(smallTextScale), hiddenNotesStart,
                hiddenNotesStart + hiddenNotesHeader.length() + hiddenNotes.length(), finalFlags);
    }
    Matcher m = KlingonContentProvider.Entry.ENTRY_PATTERN.matcher(expandedDefinition);
    while (m.find()) {

        // Strip the brackets {} to get the query.
        String query = expandedDefinition.substring(m.start() + 1, m.end() - 1);
        LookupClickableSpan viewLauncher = new LookupClickableSpan(query);

        // Process the linked entry information.
        KlingonContentProvider.Entry linkedEntry = new KlingonContentProvider.Entry(query, getBaseContext());
        // Log.d(TAG, "linkedEntry.getEntryName() = " + linkedEntry.getEntryName());

        // Delete the brackets and metadata parts of the string (which includes analysis components).
        ssb.delete(m.start() + 1 + linkedEntry.getEntryName().length(), m.end());
        ssb.delete(m.start(), m.start() + 1);
        int end = m.start() + linkedEntry.getEntryName().length();

        // Insert link to the category for a useful phrase.
        if (entry.isSentence() && !entry.getSentenceType().equals("")
                && linkedEntry.getEntryName().equals("*")) {
            // Delete the "*" placeholder.
            ssb.delete(m.start(), m.start() + 1);

            // Insert the category name.
            ssb.insert(m.start(), entry.getSentenceType());
            end += entry.getSentenceType().length() - 1;
        }

        // Set the font and link.
        // TODO: Source should link to description of the source.
        // This is true if this entry doesn't launch an EntryActivity.
        boolean disableEntryLink = linkedEntry.doNotLink() || linkedEntry.isSource() || linkedEntry.isURL();
        // The last span set on a range must have finalFlags.
        int maybeFinalFlags = disableEntryLink ? finalFlags : intermediateFlags;
        if (linkedEntry.isSource()) {
            // Names of sources are in italics.
            ssb.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), m.start(), end, maybeFinalFlags);
        } else if (linkedEntry.isURL()) {
            // Linkify URL if there is one.
            String url = linkedEntry.getURL();
            if (!url.equals("")) {
                ssb.setSpan(new URLSpan(url), m.start(), end, maybeFinalFlags);
            }
        } else if (useKlingonFont) {
            // Display the text using the Klingon font. Categories (which have an entry of "*") must
            // be handled specially.
            String klingonEntryName = !linkedEntry.getEntryName().equals("*")
                    ? linkedEntry.getEntryNameInKlingonFont()
                    : KlingonContentProvider.convertStringToKlingonFont(entry.getSentenceType());
            ssb.delete(m.start(), end);
            ssb.insert(m.start(), klingonEntryName);
            end = m.start() + klingonEntryName.length();
            ssb.setSpan(new KlingonTypefaceSpan("", klingonTypeface), m.start(), end, maybeFinalFlags);
        } else {
            // Klingon is in bold serif.
            ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), m.start(), end, intermediateFlags);
            ssb.setSpan(new TypefaceSpan("serif"), m.start(), end, maybeFinalFlags);
        }
        // If linked entry is hypothetical or extended canon, insert a "?" in front.
        if (linkedEntry.isHypothetical() || linkedEntry.isExtendedCanon()) {
            ssb.insert(m.start(), "?");
            ssb.setSpan(new RelativeSizeSpan(smallTextScale), m.start(), m.start() + 1, intermediateFlags);
            ssb.setSpan(new SuperscriptSpan(), m.start(), m.start() + 1, maybeFinalFlags);
            end++;
        }
        // Only apply colours to verbs, nouns, and affixes (exclude BLUE and WHITE).
        if (!disableEntryLink) {
            // Link to view launcher.
            ssb.setSpan(viewLauncher, m.start(), end, useColours ? intermediateFlags : finalFlags);
        }
        // Set the colour last, so it's not overridden by other spans.
        if (useColours) {
            ssb.setSpan(new ForegroundColorSpan(linkedEntry.getTextColor()), m.start(), end, finalFlags);
        }
        String linkedPos = linkedEntry.getBracketedPartOfSpeech(/* isHtml */false);
        if (!linkedPos.equals("") && linkedPos.length() > 1) {
            ssb.insert(end, linkedPos);

            int rightBracketLoc = linkedPos.indexOf(")");
            if (rightBracketLoc != -1) {
                // linkedPos is always of the form " (pos)[ (def'n N)]", we want to italicise
                // the "pos" part only.
                ssb.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), end + 2, end + rightBracketLoc,
                        finalFlags);
            }
        }

        // Rinse and repeat.
        expandedDefinition = ssb.toString();
        m = KlingonContentProvider.Entry.ENTRY_PATTERN.matcher(expandedDefinition);
    }

    // Display the entry name and definition.
    entryText.invalidate();
    entryText.setText(ssb);
    entryText.setMovementMethod(LinkMovementMethod.getInstance());
}

From source file:org.sufficientlysecure.keychain.ui.ViewKeyKeybaseFragment.java

@Override
public void onCryptoOperationSuccess(KeybaseVerificationResult result) {

    result.createNotify(getActivity()).show();

    String proofUrl = result.mProofUrl;
    String presenceUrl = result.mPresenceUrl;
    String presenceLabel = result.mPresenceLabel;

    Proof proof = mProof; // TODO: should ideally be contained in result

    String proofLabel;/*from   ww  w.j  av  a  2  s  . com*/
    switch (proof.getType()) {
    case Proof.PROOF_TYPE_TWITTER:
        proofLabel = getString(R.string.keybase_twitter_proof);
        break;
    case Proof.PROOF_TYPE_DNS:
        proofLabel = getString(R.string.keybase_dns_proof);
        break;
    case Proof.PROOF_TYPE_WEB_SITE:
        proofLabel = getString(R.string.keybase_web_site_proof);
        break;
    case Proof.PROOF_TYPE_GITHUB:
        proofLabel = getString(R.string.keybase_github_proof);
        break;
    case Proof.PROOF_TYPE_REDDIT:
        proofLabel = getString(R.string.keybase_reddit_proof);
        break;
    default:
        proofLabel = getString(R.string.keybase_a_post);
        break;
    }

    SpannableStringBuilder ssb = new SpannableStringBuilder();

    ssb.append(getString(R.string.keybase_proof_succeeded));
    StyleSpan bold = new StyleSpan(Typeface.BOLD);
    ssb.setSpan(bold, 0, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ssb.append("\n\n");
    int length = ssb.length();
    ssb.append(proofLabel);
    if (proofUrl != null) {
        URLSpan postLink = new URLSpan(proofUrl);
        ssb.setSpan(postLink, length, length + proofLabel.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    if (Proof.PROOF_TYPE_DNS == proof.getType()) {
        ssb.append(" ").append(getString(R.string.keybase_for_the_domain)).append(" ");
    } else {
        ssb.append(" ").append(getString(R.string.keybase_fetched_from)).append(" ");
    }
    length = ssb.length();
    URLSpan presenceLink = new URLSpan(presenceUrl);
    ssb.append(presenceLabel);
    ssb.setSpan(presenceLink, length, length + presenceLabel.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    if (Proof.PROOF_TYPE_REDDIT == proof.getType()) {
        ssb.append(", ").append(getString(R.string.keybase_reddit_attribution)).append(" ")
                .append(proof.getHandle()).append("?, ");
    }
    ssb.append(" ").append(getString(R.string.keybase_contained_signature));

    displaySpannableResult(ssb);
}

From source file:com.hippo.nimingban.ui.ListActivity.java

private Spanned fixURLSpan(Spanned spanned) {
    Spannable spannable;// w w  w.j  ava 2 s .c o m
    if (spanned instanceof Spannable) {
        spannable = (Spannable) spanned;
    } else {
        spannable = new SpannableString(spanned);
    }

    URLSpan[] urlSpans = spannable.getSpans(0, spanned.length(), URLSpan.class);
    if (urlSpans == null) {
        return spanned;
    }

    for (URLSpan urlSpan : urlSpans) {
        String url = urlSpan.getURL();
        if (TextUtils.isEmpty(url)) {
            spannable.removeSpan(urlSpan);
        }

        try {
            new URL(url);
        } catch (MalformedURLException e) {
            URL absoluteUrl;
            // It might be relative path
            try {
                // Use absolute url
                absoluteUrl = new URL(new URL(ACUrl.HOST), url);
                int start = spannable.getSpanStart(urlSpan);
                int end = spannable.getSpanEnd(urlSpan);
                spannable.removeSpan(urlSpan);
                spannable.setSpan(new URLSpan(absoluteUrl.toString()), start, end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            } catch (MalformedURLException e1) {
                // Can't get url
                spannable.removeSpan(urlSpan);
            }
        }
    }

    return spannable;
}