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:de.ktran.anno1404warenrechner.views.PopulationNumberDialog.java

private void setAdvancementText(int value, PopulationType.Civilization civilization) {
    String advanceTextStart = getActivity().getString(R.string.advance_to);
    String advanceName = getPopulationTypeByProgress(value, civilization).getString(getContext());
    if (advancementText != null) {
        advancementText.setText(advanceTextStart + " " + advanceName.toLowerCase(),
                TextView.BufferType.SPANNABLE);

        Spannable sp = (Spannable) advancementText.getText();
        sp.setSpan(new StyleSpan(Typeface.BOLD), advanceTextStart.length(),
                1 + advanceTextStart.length() + advanceName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }/*  w  ww.j a  va 2  s .c om*/
}

From source file:Main.java

public static void setClickable(final TextView textView) {
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    Spannable sp = (Spannable) textView.getText();
    ImageSpan[] images = sp.getSpans(0, textView.getText().length(), ImageSpan.class);

    for (ImageSpan span : images) {
        final String image_src = span.getSource();
        final int start = sp.getSpanStart(span);
        final int end = sp.getSpanEnd(span);

        ClickableSpan click_span = new ClickableSpan() {
            @Override//  w  w  w. j  ava  2s .  c  o m
            public void onClick(View widget) {
                String[] strs = image_src.split("/");
                String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/LilyClient/"
                        + strs[strs.length - 2] + "-" + strs[strs.length - 1];

                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setType("image/*");
                intent.setDataAndType(Uri.fromFile(new File(filePath)), "image/*");
                textView.getContext().startActivity(intent);

            }
        };
        ClickableSpan[] click_spans = sp.getSpans(start, end, ClickableSpan.class);
        if (click_spans.length != 0) {
            for (ClickableSpan c_span : click_spans) {
                sp.removeSpan(c_span);
            }
        }
        sp.setSpan(click_span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}

From source file:uk.os.search.android.app.SearchAdapter.java

private void setColor(TextView view, String fulltext, String subtext, int color) {
    if (subtext.isEmpty()) {
        return;//from   w w  w .j  av a2  s.c  om
    }

    view.setText(fulltext, TextView.BufferType.SPANNABLE);
    Spannable str = (Spannable) view.getText();

    List<Integer> indexes = indexesOf(fulltext.toLowerCase(Locale.getDefault()),
            subtext.toLowerCase(Locale.getDefault()));
    for (Integer index : indexes) {
        str.setSpan(new ForegroundColorSpan(color), index, index + subtext.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}

From source file:com.popdeem.sdk.uikit.adapter.PDUIFeedRecyclerViewAdapter.java

@Deprecated
private Spannable getRedemptionText(Context context, String firstName, String secondName, String reward,
        String brandName, boolean isCheckin) {
    String fullName = firstName + " " + secondName;
    String redemptionName;/*from   w w  w.  j  a v  a 2s .  c  o m*/
    if (fullName.equalsIgnoreCase(mCurrentUserName)) {
        redemptionName = "You";
    } else {
        redemptionName = fullName;
    }

    String redemptionAction;
    if (isCheckin) {
        redemptionAction = "checked in and redeemed";
    } else {
        redemptionAction = "shared an image and redeemed";
    }

    Spannable spannable = new SpannableString(
            redemptionName + " " + redemptionAction + " " + reward + " at " + brandName);
    spannable.setSpan(
            new ForegroundColorSpan(ContextCompat.getColor(context, R.color.pd_feed_item_name_text_color)), 0,
            redemptionName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannable.setSpan(
            new ForegroundColorSpan(ContextCompat.getColor(context, R.color.pd_feed_item_title_text_color)),
            (redemptionName + " " + redemptionAction).length(),
            (redemptionName + " " + redemptionAction + " ").length() + reward.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannable.setSpan(
            new ForegroundColorSpan(ContextCompat.getColor(context, R.color.pd_feed_item_title_text_color)),
            (redemptionName + " " + redemptionAction + " " + reward + " at").length(),
            (redemptionName + " " + redemptionAction + " " + reward + " at ").length() + brandName.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    return spannable;
}

From source file:com.microsoft.azure.engagement.ProductDiscountActivity.java

/**
 * Method that adds or removes a strike from a TextView object
 *
 * @param textView The textView to manage
 *///  w  w  w  .  ja v a 2  s.  c  o  m
private final void addOrRemoveStrikeTextView(TextView textView, boolean toAdd) {
    textView.setText(textView.getText().toString(), TextView.BufferType.SPANNABLE);
    final Spannable spannable = (Spannable) textView.getText();

    if (toAdd == true) {
        // Add a StrikethroughSpan style
        final StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
        spannable.setSpan(strikethroughSpan, 0, textView.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    } else {
        // Remove only StrikethroughSpan style
        final Object spans[] = spannable.getSpans(0, textView.length(), Object.class);
        for (final Object span : spans) {
            if (span instanceof StrikethroughSpan == true) {
                spannable.removeSpan(span);
                return;
            }
        }
    }
}

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

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

    View rowView;/*from   w w w  .jav  a 2s. c  om*/

    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rowView = inflater.inflate(R.layout.list_item_chat, parent, false);
    } else {
        rowView = convertView;
    }

    JSONObject p = values.get(position);
    try {
        int then = Integer.parseInt(p.getString("time"));
        long nowL = System.currentTimeMillis() / 1000;
        int now = (int) nowL;

        int ela = now - then;
        int day = 60 * 60 * 24;
        ela = ela > day ? day : ela;
        int intColor = 255 - Math.round((float) ela * 255 / day);
        intColor = intColor > 100 ? intColor : 100;
        String hexTransparency = Integer.toHexString(intColor);
        hexTransparency = hexTransparency.length() > 1 ? hexTransparency : "0" + hexTransparency;
        String hexColor = "#" + hexTransparency + "000000";
        int transparency = Color.parseColor(hexColor);

        TextView time = (TextView) rowView.findViewById(R.id.time);
        if (time != null) {
            String ts = null;
            ts = Utils.time2Ago(then);
            time.setText(ts);
            time.setTextColor(transparency);
        }

        TextView mess = (TextView) rowView.findViewById(R.id.message);
        if (mess != null) {

            final String username = p.getString("username");

            String messageString = p.getString("message");

            messageString = Html.fromHtml(messageString).toString();

            SpannableString messageSpan = Utils.replaceSmilies(context, messageString, intColor);

            if (messageString.contains("@" + loggedUser)) {
                int index = messageString.indexOf("@" + loggedUser);
                messageSpan.setSpan(new StyleSpan(Typeface.BOLD), index, index + loggedUser.length() + 1,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                messageSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#" + hexTransparency + "990000")),
                        index, index + loggedUser.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            for (String user : users) {
                if (!user.equals(loggedUser) && messageString.contains("@" + user)) {
                    int index = messageString.indexOf("@" + user);
                    messageSpan = Utils.createProfileSpan(context, index, index + user.length() + 1, user,
                            messageSpan);
                    messageSpan.setSpan(
                            new ForegroundColorSpan(Color.parseColor("#" + hexTransparency + "009900")), index,
                            index + user.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }

            Spannable userSpan = Utils.createProfileSpan(context, 0, username.length(), username,
                    new SpannableString(username + ": "));

            if (p.getString("me").equals("true"))
                userSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#" + hexTransparency + "0000FF")), 0,
                        userSpan.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            else
                userSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#" + hexTransparency + "000000")), 0,
                        userSpan.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            CharSequence full = TextUtils.concat(userSpan, messageSpan);

            mess.setTextColor(transparency);
            mess.setText(full);
            mess.setMovementMethod(LinkMovementMethod.getInstance());
            Linkify.addLinks(mess, Linkify.ALL);
            mess.setTag(p.getString("cid"));
        }

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

}

From source file:ayushi.view.adapter.ShoppingListAdapter.java

@Override
public void onBindViewHolder(final ItemViewHolder holder, final int position) {
    holder.itemName.setText(productList.get(position).getItemName());

    holder.itemDesc.setText(productList.get(position).getItemShortDesc());

    String sellCostString = Money
            .rupees(BigDecimal.valueOf(Long.valueOf(productList.get(position).getSellMRP()))).toString() + "  ";

    String buyMRP = Money.rupees(BigDecimal.valueOf(Long.valueOf(productList.get(position).getMRP())))
            .toString();//from  ww  w.  ja  v  a 2  s. com

    String costString = sellCostString + buyMRP;

    holder.itemCost.setText(costString, BufferType.SPANNABLE);

    Spannable spannable = (Spannable) holder.itemCost.getText();

    spannable.setSpan(new StrikethroughSpan(), sellCostString.length(), costString.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    mDrawableBuilder = TextDrawable.builder().beginConfig().withBorder(4).endConfig().roundRect(10);

    drawable = mDrawableBuilder.build(String.valueOf(productList.get(position).getItemName().charAt(0)),
            mColorGenerator.getColor(productList.get(position).getItemName()));

    ImageUrl = productList.get(position).getImageURL();

    holder.quanitity
            .setText(GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(position).getQuantity());

    Glide.with(context).load(ImageUrl).placeholder(drawable).error(drawable).animate(R.anim.base_slide_right_in)
            .centerCrop().into(holder.imagView);

    // Start a drag whenever the handle view it touched
    holder.imagView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
                mDragStartListener.onStartDrag(holder);
            }
            return false;
        }
    });

    holder.addItem.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(position).setQuantity(String.valueOf(

                    Integer.valueOf(
                            GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(position).getQuantity())
                            + 1));

            holder.quanitity.setText(
                    GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(position).getQuantity());

            Utils.vibrate(context);

            ((ECartHomeActivity) context).updateCheckOutAmount(
                    BigDecimal.valueOf(Long.valueOf(
                            GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(position).getSellMRP())),
                    true);

        }
    });

    holder.removeItem.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (Integer.valueOf(
                    GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(position).getQuantity()) > 2) {

                GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(position).setQuantity(String.valueOf(

                        Integer.valueOf(GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(position)
                                .getQuantity()) - 1));

                holder.quanitity.setText(
                        GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(position).getQuantity());

                ((ECartHomeActivity) context).updateCheckOutAmount(BigDecimal.valueOf(Long.valueOf(
                        GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(position).getSellMRP())),
                        false);

                Utils.vibrate(context);
            }

            else if (Integer.valueOf(
                    GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(position).getQuantity()) == 1) {
                ((ECartHomeActivity) context).updateItemCount(false);

                ((ECartHomeActivity) context).updateCheckOutAmount(BigDecimal.valueOf(Long.valueOf(
                        GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(position).getSellMRP())),
                        false);

                GlobaDataHolder.getGlobaDataHolder().getShoppingList().remove(position);

                if (Integer.valueOf(((ECartHomeActivity) context).getItemCount()) == 0) {

                    MyCartFragment.updateMyCartFragment(false);

                }

                Utils.vibrate(context);

            }

        }
    });
}

From source file:com.hitesh_sahu.retailapp.view.adapter.ShoppingListAdapter.java

@Override
public void onBindViewHolder(final ItemViewHolder holder, final int position) {
    holder.itemName.setText(productList.get(position).getItemName());

    holder.itemDesc.setText(productList.get(position).getItemShortDesc());

    String sellCostString = Money
            .rupees(BigDecimal.valueOf(Long.valueOf(productList.get(position).getSellMRP()))).toString() + "  ";

    String buyMRP = Money.rupees(BigDecimal.valueOf(Long.valueOf(productList.get(position).getMRP())))
            .toString();/*from  ww w  .  ja va  2 s  .c  om*/

    String costString = sellCostString + buyMRP;

    holder.itemCost.setText(costString, BufferType.SPANNABLE);

    Spannable spannable = (Spannable) holder.itemCost.getText();

    spannable.setSpan(new StrikethroughSpan(), sellCostString.length(), costString.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    mDrawableBuilder = TextDrawable.builder().beginConfig().withBorder(4).endConfig().roundRect(10);

    drawable = mDrawableBuilder.build(String.valueOf(productList.get(position).getItemName().charAt(0)),
            mColorGenerator.getColor(productList.get(position).getItemName()));

    ImageUrl = productList.get(position).getImageURL();

    holder.quanitity.setText(CenterRepository.getCenterRepository().getListOfProductsInShoppingList()
            .get(position).getQuantity());

    Glide.with(context).load(ImageUrl).placeholder(drawable).error(drawable).animate(R.anim.base_slide_right_in)
            .centerCrop().into(holder.imagView);

    // Start a drag whenever the handle view it touched
    holder.imagView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
                mDragStartListener.onStartDrag(holder);
            }
            return false;
        }
    });

    holder.addItem.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            CenterRepository.getCenterRepository().getListOfProductsInShoppingList().get(position)
                    .setQuantity(String.valueOf(

                            Integer.valueOf(CenterRepository.getCenterRepository()
                                    .getListOfProductsInShoppingList().get(position).getQuantity()) + 1));

            holder.quanitity.setText(CenterRepository.getCenterRepository().getListOfProductsInShoppingList()
                    .get(position).getQuantity());

            Utils.vibrate(context);

            ((ECartHomeActivity) context).updateCheckOutAmount(BigDecimal.valueOf(Long.valueOf(CenterRepository
                    .getCenterRepository().getListOfProductsInShoppingList().get(position).getSellMRP())),
                    true);

        }
    });

    holder.removeItem.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (Integer.valueOf(CenterRepository.getCenterRepository().getListOfProductsInShoppingList()
                    .get(position).getQuantity()) > 2) {

                CenterRepository.getCenterRepository().getListOfProductsInShoppingList().get(position)
                        .setQuantity(String.valueOf(

                                Integer.valueOf(CenterRepository.getCenterRepository()
                                        .getListOfProductsInShoppingList().get(position).getQuantity()) - 1));

                holder.quanitity.setText(CenterRepository.getCenterRepository()
                        .getListOfProductsInShoppingList().get(position).getQuantity());

                ((ECartHomeActivity) context).updateCheckOutAmount(
                        BigDecimal.valueOf(Long.valueOf(CenterRepository.getCenterRepository()
                                .getListOfProductsInShoppingList().get(position).getSellMRP())),
                        false);

                Utils.vibrate(context);
            }

            else if (Integer.valueOf(CenterRepository.getCenterRepository().getListOfProductsInShoppingList()
                    .get(position).getQuantity()) == 1) {
                ((ECartHomeActivity) context).updateItemCount(false);

                ((ECartHomeActivity) context).updateCheckOutAmount(
                        BigDecimal.valueOf(Long.valueOf(CenterRepository.getCenterRepository()
                                .getListOfProductsInShoppingList().get(position).getSellMRP())),
                        false);

                CenterRepository.getCenterRepository().getListOfProductsInShoppingList().remove(position);

                if (Integer.valueOf(((ECartHomeActivity) context).getItemCount()) == 0) {

                    MyCartFragment.updateMyCartFragment(false);

                }

                Utils.vibrate(context);

            }

        }
    });
}

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

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

    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);/* w ww .  j a  v a2s  .  com*/
    } else
        textView.setText(originalText);
}

From source file:org.miaowo.miaowo.util.Html.java

private static void setSpanFromMark(Spannable text, Object mark, Object... spans) {
    int where = text.getSpanStart(mark);
    text.removeSpan(mark);//from   w w w  .  j a v a  2  s  .c om
    int len = text.length();
    if (where != len) {
        for (Object span : spans) {
            text.setSpan(span, where, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
}