Example usage for android.text Spannable setSpan

List of usage examples for android.text Spannable setSpan

Introduction

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

Prototype

public void setSpan(Object what, int start, int end, int flags);

Source Link

Document

Attach the specified markup object to the range start…end of the text, or move the object to that range if it was already attached elsewhere.

Usage

From source file:com.thatkawaiiguy.meleehandbook.adapter.SearchAdapter.java

private void highlightAndCut(String search, String originalText, TextView textView) {
    int startPos = originalText.toLowerCase().indexOf(search);
    int endPos = startPos + search.length();

    int wholeStart = originalText.toLowerCase().indexOf(" ", startPos - 100);
    if (wholeStart == -1)
        wholeStart = 0;/*from   w w  w  .  j av a  2  s  .  c o  m*/

    if (originalText.substring(wholeStart, wholeStart + 1).equals(","))
        wholeStart += 1;

    int wholeEnd = originalText.toLowerCase().indexOf(" ",
            endPos + 100 < originalText.length() - 1 ? endPos + 100 : endPos - search.length() - 1);

    if (wholeEnd == -1)
        wholeEnd = endPos;

    originalText = originalText.substring(wholeStart, wholeEnd).trim() + " (Click for more)";

    startPos = originalText.toLowerCase().indexOf(search);
    endPos = startPos + search.length();
    // This should always be true, just a sanity check
    if (startPos != -1) {
        Spannable spannable = new SpannableString(originalText);
        ColorStateList yellowColor = new ColorStateList(new int[][] { new int[] {} },
                new int[] { ContextCompat.getColor(mContext, R.color.overscroll_color) });
        TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, yellowColor, null);

        spannable.setSpan(highlightSpan, startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(spannable);
    } else
        textView.setText(originalText);
}

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

private void setToolbar() {
    toolbarTB.setBackgroundColor(ContextCompat.getColor(this, MainActivity.primaryColor));

    MainActivity.setStatusBar(this);

    toolbarTB.getNavigationIcon().setColorFilter(ContextCompat.getColor(this, MainActivity.primaryTextColor),
            PorterDuff.Mode.SRC_ATOP);//from w  w w  .  ja  v a 2 s. c o m

    Spannable toolbarTitle = new SpannableString(getString(R.string.settings));
    toolbarTitle.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, MainActivity.primaryTextColor)),
            0, toolbarTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    toolbarTB.setTitle(toolbarTitle);
}

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

/**
 * Stylify text view to primary colour and no underline
 * @param c App context/*  ww w.java  2s  . c  om*/
 * @param t TextView
 */
public static void styleLinkifiedTextView(Context c, TextView t) {
    // Get individual spans and replace them with clickable ones.
    Spannable s = new SpannableString(t.getText());
    URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
    for (URLSpan span : spans) {
        int start = s.getSpanStart(span);
        int end = s.getSpanEnd(span);
        s.removeSpan(span);
        span = new URLSpanNoUnderline(c, span.getURL());
        s.setSpan(span, start, end, 0);
    }

    t.setText(s);
    // Need to set this to allow for clickable TextView links.
    if (!(t instanceof HtmlTextView)) {
        t.setMovementMethod(LinkMovementMethod.getInstance());
    }
}

From source file:es.usc.citius.servando.calendula.activities.CalendarActivity.java

public CharSequence addPickupList(CharSequence msg, List<PickupInfo> pks) {

    Paint textPaint = new Paint();
    //obviously, we have to set textSize into Paint object
    textPaint.setTextSize(getResources().getDimensionPixelOffset(R.dimen.medium_font_size));
    Paint.FontMetricsInt fontMetrics = textPaint.getFontMetricsInt();

    for (PickupInfo p : pks) {
        Patient patient = pickupUtils.getPatient(p);
        int color = patient.color();
        String str = "       " + p.medicine().name() + " (" + dtf2.format(p.from().toDate()) + " - "
                + dtf2.format(p.to().toDate()) + ")\n";
        Spannable text = new SpannableString(str);
        text.setSpan(new ForegroundColorSpan(color), 0, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        Drawable d = getResources().getDrawable(AvatarMgr.res(patient.avatar()));
        d.setBounds(0, 0, fontMetrics.bottom, fontMetrics.bottom);
        ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
        text.setSpan(span, 0, 5, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        msg = TextUtils.concat(msg, text);
    }/*  ww w  . ja  va 2  s.  c  om*/
    return msg;
}

From source file:com.discord.chipsview.ChipsView.java

private void addLeadingMarginSpan() {
    Spannable spannable = mEditText.getText();
    if (mCurrentEditTextSpan != null) {
        spannable.removeSpan(mCurrentEditTextSpan);
    }//from  w w w. j a  v a  2 s.c  o m
    spannable.setSpan(mCurrentEditTextSpan, 0, 0, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    mEditText.setText(spannable);
}

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

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View rowView = inflater.inflate(R.layout.list_item_commit, parent, false);

    final View shell = rowView.findViewById(R.id.detail_shell);

    rowView.setOnClickListener(new View.OnClickListener() {
        @Override//from w ww  . j a  va2s .c  o m
        public void onClick(View view) {
            boolean visible = shell.getVisibility() == View.VISIBLE;

            shell.setVisibility(visible ? View.GONE : View.VISIBLE);

            context.setCommitVisible(position, !visible);

        }
    });

    final JSONObject p = values.get(position);

    TextView title = (TextView) rowView.findViewById(R.id.title);
    TextView descV = (TextView) rowView.findViewById(R.id.desc);
    TextView defV = (TextView) rowView.findViewById(R.id.def);
    TextView usersV = (TextView) rowView.findViewById(R.id.users);
    TextView youV = (TextView) rowView.findViewById(R.id.you);

    try {

        if (p.getBoolean("open"))
            shell.setVisibility(View.VISIBLE);

        title.setText(p.getString("title"));
        descV.setText(p.getString("description"));

        String length = p.getString("length");
        String time = p.getString("time");
        final String cid = p.getString("cid");

        String def = "";

        boolean repeat = false;

        if (length.indexOf(":") > 0) {
            repeat = true;
            String[] lengtha = length.split(":");
            def += lengtha[0] + " minutes walking and " + lengtha[1] + " minutes sitting";
        } else
            def += length + " minutes total meditation";

        String period = p.getString("period");

        String day = p.getString("day");

        if (period.equals("daily")) {
            if (repeat)
                def += " every day";
            else
                def += " per day";
        } else if (period.equals("weekly")) {
            if (repeat)
                def += " every " + dow[Integer.parseInt(day)];
            else
                def += " per week";
        } else if (period.equals("monthly")) {
            if (repeat)
                def += " on the " + day
                        + (day.substring(day.length() - 1).equals("1") ? "st"
                                : (day.substring(day.length() - 1).equals("2") ? "nd"
                                        : (day.substring(day.length() - 1).equals("3") ? "rd" : "th")))
                        + " day of the month";
            else
                def += " per month";
        } else if (period.equals("yearly")) {
            if (repeat)
                def += " on the " + day
                        + (day.substring(day.length() - 1).equals("1") ? "st"
                                : (day.substring(day.length() - 1).equals("2") ? "nd"
                                        : (day.substring(day.length() - 1).equals("3") ? "rd" : "th")))
                        + " day of the year";
            else
                def += " per year";
        }

        if (!time.equals("any")) {
            Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            utc.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time.split(":")[0]));
            utc.set(Calendar.MINUTE, Integer.parseInt(time.split(":")[1]));

            Calendar here = Calendar.getInstance();
            here.setTimeInMillis(utc.getTimeInMillis());

            int hours = here.get(Calendar.HOUR_OF_DAY);
            int minutes = here.get(Calendar.MINUTE);

            def += " at " + (time.length() == 4 ? "0" : "") + time.replace(":", "") + "h UTC <i>("
                    + (hours > 12 ? hours - 12 : hours) + ":" + ((minutes < 10 ? "0" : "") + minutes) + " "
                    + (hours > 11 && hours < 24 ? "PM" : "AM") + " your time)</i>";
        }

        defV.setText(Html.fromHtml(def));

        JSONObject usersJ = p.getJSONObject("users");

        ArrayList<String> committedArray = new ArrayList<String>();

        // collect into array

        for (int i = 0; i < usersJ.names().length(); i++) {
            try {
                String j = usersJ.names().getString(i);
                String k = j;
                //                    if(j.equals(p.getString("creator")))
                //                        k = "["+j+"]";
                committedArray.add(k);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

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

        // add spans

        int committed = -1;

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

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

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

        for (int i = 0; i < committedArray.size(); i++) {
            try {

                final String oneCom = committedArray.get(i);
                String userCom = usersJ.getString(oneCom);
                //String userCom = usersJ.getString(oneCom.replace("[", "").replace("]", ""));

                //if(oneCom.replace("[","").replace("]","").equals(loggedUser))
                if (oneCom.equals(loggedUser))
                    committed = Integer.parseInt(userCom);

                int end = pos + oneCom.length();

                ClickableSpan clickable = new ClickableSpan() {

                    @Override
                    public void onClick(View widget) {
                        context.showProfile(oneCom);
                    }

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

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

                String color = Utils.makeRedGreen(Integer.parseInt(userCom), true);

                span.setSpan(new ForegroundColorSpan(Color.parseColor("#FF" + color)), pos, end,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                pos += oneCom.length() + 2;

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        usersV.setText(span);
        usersV.setMovementMethod(new LinkMovementMethod());

        if (loggedUser != null && loggedUser.length() > 0) {
            LinearLayout bl = (LinearLayout) rowView.findViewById(R.id.commit_buttons);
            if (!usersJ.has(loggedUser)) {
                Button commitB = new Button(context);
                commitB.setId(R.id.commit_button);
                commitB.setText(R.string.commit);
                commitB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                        nvp.add(new BasicNameValuePair("full_update", "true"));

                        context.doSubmit("commitform_" + cid, nvp, true);
                    }
                });
                bl.addView(commitB);
            } else {
                Button commitB = new Button(context);
                commitB.setId(R.id.uncommit_button);
                commitB.setText(R.string.uncommit);
                commitB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                        nvp.add(new BasicNameValuePair("full_update", "true"));

                        context.doSubmit("uncommitform_" + cid, nvp, true);
                    }
                });
                bl.addView(commitB);
            }

            if (loggedUser.equals(p.getString("creator")) || context.isAdmin) {
                Button commitB2 = new Button(context);
                commitB2.setId(R.id.edit_commit_button);
                commitB2.setText(R.string.edit);
                commitB2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent i = new Intent(context, ActivityCommit.class);
                        i.putExtra("commitment", p.toString());
                        context.startActivity(i);
                    }
                });
                bl.addView(commitB2);

                Button commitB3 = new Button(context);
                commitB3.setId(R.id.uncommit_button);
                commitB3.setText(R.string.delete);
                commitB3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                        nvp.add(new BasicNameValuePair("full_update", "true"));

                        context.doSubmit("delcommitform_" + cid, nvp, true);
                    }
                });
                bl.addView(commitB3);
            }

        }

        if (committed > -1) {
            int color = Color.parseColor("#FF" + Utils.makeRedGreen(committed, false));
            rowView.setBackgroundColor(color);
        }

        if (committed != -1) {
            youV.setText(String.format(context.getString(R.string.you_commit_x), committed));
            youV.setVisibility(View.VISIBLE);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return rowView;
}

From source file:org.catrobat.catroid.ui.fragment.AddBrickFragment.java

public void onBrickChecked() {
    if (actionMode == null) {
        return;/* www. j  a v  a 2s. c o m*/
    }

    int numberOfSelectedItems = adapter.getAmountOfCheckedItems();

    if (numberOfSelectedItems == 0) {
        actionMode.setTitle(actionModeTitle);
    } else {
        String appendix = multipleItemAppendixActionMode;

        if (numberOfSelectedItems == 1) {
            appendix = singleItemAppendixActionMode;
        }

        String numberOfItems = Integer.toString(numberOfSelectedItems);
        String completeTitle = actionModeTitle + " " + numberOfItems + " " + appendix;

        int titleLength = actionModeTitle.length();

        Spannable completeSpannedTitle = new SpannableString(completeTitle);
        completeSpannedTitle.setSpan(
                new ForegroundColorSpan(getResources().getColor(R.color.actionbar_title_color)),
                titleLength + 1, titleLength + (1 + numberOfItems.length()),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        actionMode.setTitle(completeSpannedTitle);
    }
}

From source file:com.app.blockydemo.ui.fragment.ScriptFragment.java

private void updateActionModeTitle() {
    int numberOfSelectedItems = adapter.getAmountOfCheckedItems();

    String completeTitle;/*from   w  ww .jav a 2  s.c o  m*/
    switch ((Integer) actionMode.getTag()) {
    case ACTION_MODE_COPY:
        completeTitle = getResources().getQuantityString(R.plurals.number_of_bricks_to_copy,
                numberOfSelectedItems, numberOfSelectedItems);
        break;
    case ACTION_MODE_DELETE:
        completeTitle = getResources().getQuantityString(R.plurals.number_of_bricks_to_delete,
                numberOfSelectedItems, numberOfSelectedItems);
        break;
    default:
        throw new IllegalArgumentException("Wrong or unhandled tag in ActionMode.");
    }

    int indexOfNumber = completeTitle.indexOf(' ') + 1;
    Spannable completeSpannedTitle = new SpannableString(completeTitle);
    completeSpannedTitle.setSpan(
            new ForegroundColorSpan(getResources().getColor(R.color.actionbar_title_color)), indexOfNumber,
            indexOfNumber + String.valueOf(numberOfSelectedItems).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    actionMode.setTitle(completeSpannedTitle);
}

From source file:com.github.andrewlord1990.snackbarbuilder.SnackbarBuilder.java

/**
 * Add some text to append to the message shown on the Snackbar and a colour to make it.
 *
 * @param message Text to append to the Snackbar message.
 * @param color   Colour to make the appended text.
 * @return This instance./*from w w w  .  ja v a  2s.co  m*/
 */
public SnackbarBuilder appendMessage(CharSequence message, @ColorInt int color) {
    initialiseAppendMessages();
    Spannable spannable = new SpannableString(message);
    spannable.setSpan(new ForegroundColorSpan(color), 0, spannable.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    appendMessages.append(spannable);
    return this;
}

From source file:org.catrobat.catroid.ui.fragment.BackPackSoundFragment.java

private void updateActionModeTitle() {
    int numberOfSelectedItems = adapter.getAmountOfCheckedItems();

    if (numberOfSelectedItems == 0) {
        actionMode.setTitle(actionModeTitle);
    } else {/* w  ww  . ja v  a 2  s. c  o m*/
        String appendix = multipleItemAppendixDeleteActionMode;

        if (numberOfSelectedItems == 1) {
            appendix = singleItemAppendixDeleteActionMode;
        }

        String numberOfItems = Integer.toString(numberOfSelectedItems);
        String completeTitle = actionModeTitle + " " + numberOfItems + " " + appendix;

        int titleLength = actionModeTitle.length();

        Spannable completeSpannedTitle = new SpannableString(completeTitle);
        completeSpannedTitle.setSpan(
                new ForegroundColorSpan(getResources().getColor(R.color.actionbar_title_color)),
                titleLength + 1, titleLength + (1 + numberOfItems.length()),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        actionMode.setTitle(completeSpannedTitle);
    }
}