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:com.android.mail.browse.ConversationItemView.java

private void createSnippet() {
    final String snippet = mHeader.conversation.getSnippet();
    final Spannable displayedStringBuilder = new SpannableString(snippet);

    // measure the width of the folders which overlap the snippet view
    final int folderWidth = mHeader.folderDisplayer.measureFolders(mCoordinates);

    // size the snippet view by subtracting the folder width from the maximum snippet width
    final int snippetWidth = mCoordinates.maxSnippetWidth - folderWidth;
    final int snippetHeight = mCoordinates.snippetHeight;
    mSnippetTextView.setLayoutParams(new ViewGroup.LayoutParams(snippetWidth, snippetHeight));
    mSnippetTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mCoordinates.snippetFontSize);
    layoutViewExactly(mSnippetTextView, snippetWidth, snippetHeight);

    mSnippetTextView.setText(displayedStringBuilder);
}

From source file:com.todoroo.astrid.adapter.UpdateAdapter.java

private static CharSequence getLinkSpan(final AstridActivity activity, UserActivity update, String targetName,
        String linkColor, String linkType) {
    if (TASK_LINK_TYPE.equals(linkType)) {
        final String taskId = update.getValue(UserActivity.TARGET_ID);
        if (RemoteModel.isValidUuid(taskId)) {
            SpannableString taskSpan = new SpannableString(targetName);
            taskSpan.setSpan(new ClickableSpan() {
                @Override//w w  w  . ja v  a  2 s. c o m
                public void onClick(View widget) {
                    if (activity != null) // TODO: This shouldn't happen, but sometimes does
                        activity.onTaskListItemClicked(taskId);
                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setUnderlineText(false);
                }
            }, 0, targetName.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            return taskSpan;
        } else {
            return Html.fromHtml(linkify(targetName, linkColor));
        }
    }
    return null;
}

From source file:org.onebusaway.android.report.ui.Open311ProblemFragment.java

/**
 * Dynamically creates radio buttons//from w  w w .j  av  a  2  s .c  o m
 *
 * @param open311Attribute contains the open311 attributes
 */
private void createSingleValueList(Open311Attribute open311Attribute) {
    ArrayList<Object> values = (ArrayList<Object>) open311Attribute.getValues();
    if (values != null && values.size() > 0) {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.report_issue_single_value_list_item,
                null, false);
        layout.setSaveEnabled(true);
        ((ImageView) layout.findViewById(R.id.ri_ic_radio))
                .setColorFilter(getResources().getColor(R.color.material_gray));

        Spannable word = new SpannableString(open311Attribute.getDescription());
        ((TextView) layout.findViewById(R.id.risvli_textView)).setText(word);

        if (open311Attribute.getRequired()) {
            Spannable wordTwo = new SpannableString(" *Required");
            wordTwo.setSpan(new ForegroundColorSpan(Color.RED), 0, wordTwo.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            ((TextView) layout.findViewById(R.id.risvli_textView)).append(wordTwo);
        }

        RadioGroup rg = (RadioGroup) layout.findViewById(R.id.risvli_radioGroup);
        rg.setOrientation(RadioGroup.VERTICAL);

        // Restore view state from attribute result hash map
        AttributeValue av = mAttributeValueHashMap.get(open311Attribute.getCode());
        String entryValue = null;
        if (av != null) {
            entryValue = av.getSingleValue();
        }

        for (int i = 0; i < values.size(); i++) {
            LinkedHashMap<String, String> value = (LinkedHashMap<String, String>) values.get(i);
            RadioButton rb = new RadioButton(getActivity());
            rg.addView(rb); //the RadioButtons are added to the radioGroup instead of the layout
            String attributeKey = "";
            String attributeValue = "";
            for (LinkedHashMap.Entry<String, String> entry : value.entrySet()) {
                if (Open311Attribute.NAME.equals(entry.getKey())) {
                    rb.setText(entry.getValue());
                    if (entryValue != null && entryValue.equalsIgnoreCase(entry.getValue())) {
                        rb.setChecked(true);
                    }
                    attributeKey = open311Attribute.getCode() + entry.getValue();
                } else if (Open311Attribute.KEY.equals(entry.getKey())) {
                    attributeValue = entry.getValue();
                }
            }
            mOpen311AttributeKeyNameMap.put(attributeKey, attributeValue);
        }

        mInfoLayout.addView(layout);
        mDynamicAttributeUIMap.put(open311Attribute.getCode(), rg);
    }
}

From source file:com.jecelyin.editor.v2.core.text.TextUtils.java

/**
 * Returns the original text if it fits in the specified width
 * given the properties of the specified Paint,
 * or, if it does not fit, a copy with ellipsis character added
 * at the specified edge or center.//www.j  ava 2 s  .  c o  m
 * If <code>preserveLength</code> is specified, the returned copy
 * will be padded with zero-width spaces to preserve the original
 * length and offsets instead of truncating.
 * If <code>callback</code> is non-null, it will be called to
 * report the start and end of the ellipsized range.
 *
 * @hide
 */
public static CharSequence ellipsize(CharSequence text, TextPaint paint, float avail, TruncateAt where,
        boolean preserveLength, EllipsizeCallback callback, TextDirectionHeuristic textDir, String ellipsis) {

    int len = text.length();

    MeasuredText mt = MeasuredText.obtain();
    try {
        float width = setPara(mt, paint, text, 0, text.length(), textDir);

        if (width <= avail) {
            if (callback != null) {
                callback.ellipsized(0, 0);
            }

            return text;
        }

        // XXX assumes ellipsis string does not require shaping and
        // is unaffected by style
        float ellipsiswid = paint.measureText(ellipsis);
        avail -= ellipsiswid;

        int left = 0;
        int right = len;
        if (avail < 0) {
            // it all goes
        } else if (where == TruncateAt.START) {
            right = len - mt.breakText(len, false, avail);
        } else if (where == TruncateAt.END || where == TruncateAt.END_SMALL) {
            left = mt.breakText(len, true, avail);
        } else {
            right = len - mt.breakText(len, false, avail / 2);
            avail -= mt.measure(right, len);
            left = mt.breakText(right, true, avail);
        }

        if (callback != null) {
            callback.ellipsized(left, right);
        }

        char[] buf = mt.mChars;
        Spanned sp = text instanceof Spanned ? (Spanned) text : null;

        int remaining = len - (right - left);
        if (preserveLength) {
            if (remaining > 0) { // else eliminate the ellipsis too
                buf[left++] = ellipsis.charAt(0);
            }
            for (int i = left; i < right; i++) {
                buf[i] = ZWNBS_CHAR;
            }
            String s = new String(buf, 0, len);
            if (sp == null) {
                return s;
            }
            SpannableString ss = new SpannableString(s);
            copySpansFrom(sp, 0, len, Object.class, ss, 0);
            return ss;
        }

        if (remaining == 0) {
            return "";
        }

        if (sp == null) {
            StringBuilder sb = new StringBuilder(remaining + ellipsis.length());
            sb.append(buf, 0, left);
            sb.append(ellipsis);
            sb.append(buf, right, len - right);
            return sb.toString();
        }

        SpannableStringBuilder ssb = new SpannableStringBuilder();
        ssb.append(text, 0, left);
        ssb.append(ellipsis);
        ssb.append(text, right, len);
        return ssb;
    } finally {
        MeasuredText.recycle(mt);
    }
}

From source file:com.lloydtorres.stately.helpers.SparkleHelper.java

/**
 * Overloaded to deal with spoilers./*from w w  w .  j a va 2 s.  co  m*/
 */
public static void setStyledTextView(Context c, TextView t, String holder, List<Spoiler> spoilers,
        FragmentManager fm) {
    if (t instanceof HtmlTextView) {
        try {
            ((HtmlTextView) t).setHtml(holder);
        } catch (Exception e) {
            logError(e.toString());
            t.setText(c.getString(R.string.bbcode_parse_error));
            t.setTypeface(t.getTypeface(), Typeface.ITALIC);
        }
    } else {
        t.setText(fromHtml(holder));
    }

    // Deal with spoilers here
    styleLinkifiedTextView(c, t); // Ensures TextView contains a spannable
    Spannable span = new SpannableString(t.getText());
    String rawSpan = span.toString();
    int startFromIndex = 0;

    for (int i = 0; i < spoilers.size(); i++) {
        Spoiler s = spoilers.get(i);
        int start = rawSpan.indexOf(s.replacer, startFromIndex);
        if (start != -1) {
            int end = start + s.replacer.length();
            startFromIndex = end;
            SpoilerSpan clickyDialog = new SpoilerSpan(c, s, fm);
            span.setSpan(clickyDialog, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    t.setText(span);
}

From source file:org.sirimangalo.meditationplus.ActivityMain.java

private void populateMeds(JSONArray meds) {
    if (findViewById(R.id.med_list) == null)
        return;/*from  w w  w.j av a 2s.  c  o  m*/
    medList = (ListView) findViewById(R.id.med_list);

    medArray = new ArrayList<JSONObject>();
    for (int i = 0; i < meds.length(); i++) {
        try {
            JSONObject med = meds.getJSONObject(i);

            if (med.getString("username").equals(username)) {
                if (startMeditating) {
                    startMeditating = false;

                    if (lastWalking > 0 || lastSitting > 0)
                        scheduleClient.setAlarmForNotification(lastWalking, lastSitting);
                }

                if (med.getString("type").equals("love")) {
                    special = "love";
                    Spannable span = new SpannableString("LOVE");
                    span.setSpan(new ForegroundColorSpan(Color.RED), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    span.setSpan(new ForegroundColorSpan(Color.YELLOW), 1, 2,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    span.setSpan(new ForegroundColorSpan(Color.GREEN), 2, 3,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    span.setSpan(new ForegroundColorSpan(Color.BLUE), 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    medButton.setText(span);
                } else {
                    special = "none";
                    medButton.setText(R.string.start);
                }

            }

            medArray.add(med);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    TextView emptyText = (TextView) findViewById(android.R.id.empty);
    medList.setEmptyView(emptyText);

    AdapterMed adapter = new AdapterMed(this, R.layout.list_item_med, medArray, postHandler);
    medList.setAdapter(adapter);
}

From source file:github.daneren2005.dsub.util.Util.java

private static void showDialog(Context context, int icon, String title, String message, boolean linkify) {
    SpannableString ss = new SpannableString(message);
    if (linkify) {
        Linkify.addLinks(ss, Linkify.ALL);
    }// w  ww  .ja v a 2  s .  c o  m

    AlertDialog dialog = new AlertDialog.Builder(context).setIcon(icon).setTitle(title).setMessage(ss)
            .setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int i) {
                    dialog.dismiss();
                }
            }).show();

    ((TextView) dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}

From source file:org.onebusaway.android.report.ui.Open311ProblemFragment.java

/**
 * Dynamically creates checkboxes/*  w  w  w .  j a  va  2  s . c o m*/
 *
 * @param open311Attribute contains the open311 attributes
 */
private void createMultiValueList(Open311Attribute open311Attribute) {
    ArrayList<Object> values = (ArrayList<Object>) open311Attribute.getValues();
    if (values != null && values.size() > 0) {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.report_issue_multi_value_list_item,
                null, false);

        ((ImageView) layout.findViewById(R.id.ri_ic_checkbox))
                .setColorFilter(getResources().getColor(R.color.material_gray));

        Spannable word = new SpannableString(open311Attribute.getDescription());
        ((TextView) layout.findViewById(R.id.rimvli_textView)).setText(word);

        if (open311Attribute.getRequired()) {
            Spannable wordTwo = new SpannableString(" *Required");
            wordTwo.setSpan(new ForegroundColorSpan(Color.RED), 0, wordTwo.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            ((TextView) layout.findViewById(R.id.rimvli_textView)).append(wordTwo);
        }

        // Restore view state from attribute result hash map
        AttributeValue av = mAttributeValueHashMap.get(open311Attribute.getCode());

        LinearLayout cg = (LinearLayout) layout.findViewById(R.id.rimvli_checkBoxGroup);
        for (int i = 0; i < values.size(); i++) {
            LinkedHashMap<String, String> value = (LinkedHashMap<String, String>) values.get(i);
            CheckBox cb = new CheckBox(getActivity());
            cg.addView(cb);
            String attributeKey = "";
            String attributeValue = "";
            for (LinkedHashMap.Entry<String, String> entry : value.entrySet()) {
                if (Open311Attribute.NAME.equals(entry.getKey())) {
                    cb.setText(entry.getValue());
                    if (av != null && av.getValues().contains(entry.getValue())) {
                        cb.setChecked(true);
                    }
                    attributeKey = open311Attribute.getCode() + entry.getValue();
                } else if (Open311Attribute.KEY.equals(entry.getKey())) {
                    attributeValue = entry.getValue();
                }
            }
            mOpen311AttributeKeyNameMap.put(attributeKey, attributeValue);
        }

        mInfoLayout.addView(layout);
        mDynamicAttributeUIMap.put(open311Attribute.getCode(), cg);
    }
}

From source file:com.bt.heliniumstudentapp.MainActivity.java

protected static void setToolbarTitle(AppCompatActivity context, String title, String subtitle) {
    final Spannable toolbarTitle = new SpannableString(title);
    toolbarTitle.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, primaryTextColor)), 0,
            toolbarTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    try {/*w ww . j a  v  a2  s  .  co m*/
        context.getSupportActionBar().setTitle(toolbarTitle);
    } catch (NullPointerException e) {
        return;
    }

    if (subtitle != null) {
        final Spannable toolbarSubtitle = new SpannableString(subtitle);
        toolbarSubtitle.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, secondaryTextColor)), 0,
                toolbarSubtitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        context.getSupportActionBar().setSubtitle(toolbarSubtitle);
    }
}

From source file:org.sirimangalo.meditationplus.ActivityMain.java

private void populateOnline(JSONArray onlines) {

    if (onlines.length() == 0) {
        onlineList.setVisibility(View.GONE);
        return;/*from   w  ww.  j  av  a 2 s .  com*/
    }

    onlineList.setVisibility(View.VISIBLE);

    ArrayList<JSONObject> onlineArray = new ArrayList<JSONObject>();
    ArrayList<String> onlineNamesArray = new ArrayList<String>();

    // collect into array

    for (int i = 0; i < onlines.length(); i++) {
        try {
            JSONObject a = onlines.getJSONObject(i);
            onlineArray.add(a);
            onlineNamesArray.add(a.getString("username"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    String text = getString(R.string.online) + " ";

    // add spans

    int pos = text.length(); // start after "Online: "

    text += TextUtils.join(", ", onlineNamesArray);
    Spannable span = new SpannableString(text);

    span.setSpan(new StyleSpan(Typeface.BOLD), 0, pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // bold the "Online: "

    Drawable android = context.getResources().getDrawable(R.drawable.android);
    android.setBounds(0, 0, 48, 32);

    for (JSONObject oneOnA : onlineArray) {
        try {
            final String oneOn = oneOnA.getString("username");

            int end = pos + oneOn.length();

            boolean isMed = false;

            for (int j = 0; j < jsonList.length(); j++) {
                JSONObject user = jsonList.getJSONObject(j);
                String username = user.getString("username");
                if (username.equals(oneOn))
                    isMed = true;
            }

            if (oneOnA.getString("source").equals("android")) {
                ImageSpan image = new ImageSpan(android, ImageSpan.ALIGN_BASELINE);
                span.setSpan(image, pos - 1, pos, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            }

            ClickableSpan clickable = new ClickableSpan() {

                @Override
                public void onClick(View widget) {
                    showProfile(oneOn);
                }

            };
            span.setSpan(clickable, pos, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            span.setSpan(new UnderlineSpan() {
                public void updateDrawState(TextPaint tp) {
                    tp.setUnderlineText(false);
                }
            }, pos, end, 0);

            span.setSpan(new ForegroundColorSpan(isMed ? 0xFF009900 : 0xFFFF9900), pos, end,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            pos += oneOn.length() + 2;

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    onlineList.setText(span);
    onlineList.setMovementMethod(LinkMovementMethod.getInstance());

}