Example usage for android.text Spanned SPAN_EXCLUSIVE_EXCLUSIVE

List of usage examples for android.text Spanned SPAN_EXCLUSIVE_EXCLUSIVE

Introduction

In this page you can find the example usage for android.text Spanned SPAN_EXCLUSIVE_EXCLUSIVE.

Prototype

int SPAN_EXCLUSIVE_EXCLUSIVE

To view the source code for android.text Spanned SPAN_EXCLUSIVE_EXCLUSIVE.

Click Source Link

Document

Spans of type SPAN_EXCLUSIVE_EXCLUSIVE do not expand to include text inserted at either their starting or ending point.

Usage

From source file:org.telegram.ui.Cells.DialogCell.java

public void buildLayout() {
    String nameString = "";
    String timeString = "";
    String countString = null;//from  w  ww  .  jav  a2 s  .com
    CharSequence messageString = "";
    CharSequence printingString = null;
    if (isDialogCell) {
        printingString = MessagesController.getInstance().printingStrings.get(currentDialogId);
    }
    TextPaint currentNamePaint = namePaint;
    TextPaint currentMessagePaint = messagePaint;
    boolean checkMessage = true;

    drawNameGroup = false;
    drawNameBroadcast = false;
    drawNameLock = false;
    drawNameBot = false;
    drawVerified = false;

    if (encryptedChat != null) {
        drawNameLock = true;
        nameLockTop = AndroidUtilities.dp(16.5f);
        if (!LocaleController.isRTL) {
            nameLockLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline);
            nameLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline + 4)
                    + lockDrawable.getIntrinsicWidth();
        } else {
            nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(AndroidUtilities.leftBaseline)
                    - lockDrawable.getIntrinsicWidth();
            nameLeft = AndroidUtilities.dp(14);
        }
    } else {
        if (chat != null) {
            if (chat.id < 0 || ChatObject.isChannel(chat) && !chat.megagroup) {
                drawNameBroadcast = true;
                nameLockTop = AndroidUtilities.dp(16.5f);
            } else {
                drawNameGroup = true;
                nameLockTop = AndroidUtilities.dp(17.5f);
            }
            drawVerified = chat.verified;

            if (!LocaleController.isRTL) {
                nameLockLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline);
                nameLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline + 4)
                        + (drawNameGroup ? groupDrawable.getIntrinsicWidth()
                                : broadcastDrawable.getIntrinsicWidth());
            } else {
                nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(AndroidUtilities.leftBaseline)
                        - (drawNameGroup ? groupDrawable.getIntrinsicWidth()
                                : broadcastDrawable.getIntrinsicWidth());
                nameLeft = AndroidUtilities.dp(14);
            }
        } else {
            if (!LocaleController.isRTL) {
                nameLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline);
            } else {
                nameLeft = AndroidUtilities.dp(14);
            }
            if (user != null) {
                if (user.bot) {
                    drawNameBot = true;
                    nameLockTop = AndroidUtilities.dp(16.5f);
                    if (!LocaleController.isRTL) {
                        nameLockLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline);
                        nameLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline + 4)
                                + botDrawable.getIntrinsicWidth();
                    } else {
                        nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(AndroidUtilities.leftBaseline)
                                - botDrawable.getIntrinsicWidth();
                        nameLeft = AndroidUtilities.dp(14);
                    }
                }
                drawVerified = user.verified;
            }
        }
    }

    int lastDate = lastMessageDate;
    if (lastMessageDate == 0 && message != null) {
        lastDate = message.messageOwner.date;
    }

    if (isDialogCell) {
        draftMessage = DraftQuery.getDraft(currentDialogId);
        if (draftMessage != null
                && (TextUtils.isEmpty(draftMessage.message) && draftMessage.reply_to_msg_id == 0
                        || lastDate > draftMessage.date && unreadCount != 0)
                || ChatObject.isChannel(chat) && !chat.megagroup && !chat.creator && !chat.editor
                || chat != null && (chat.left || chat.kicked)) {
            draftMessage = null;
        }
    } else {
        draftMessage = null;
    }

    if (printingString != null) {
        lastPrintString = messageString = printingString;
        currentMessagePaint = messagePrintingPaint;
    } else {
        lastPrintString = null;

        if (draftMessage != null) {
            checkMessage = false;
            if (TextUtils.isEmpty(draftMessage.message)) {
                String draftString = LocaleController.getString("Draft", R.string.Draft);
                SpannableStringBuilder stringBuilder = SpannableStringBuilder.valueOf(draftString);
                stringBuilder.setSpan(new ForegroundColorSpan(Theme.DIALOGS_DRAFT_TEXT_COLOR), 0,
                        draftString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                messageString = stringBuilder;
            } else {
                String mess = draftMessage.message;
                if (mess.length() > 150) {
                    mess = mess.substring(0, 150);
                }
                String draftString = LocaleController.getString("Draft", R.string.Draft);
                SpannableStringBuilder stringBuilder = SpannableStringBuilder
                        .valueOf(String.format("%s: %s", draftString, mess.replace('\n', ' ')));
                stringBuilder.setSpan(new ForegroundColorSpan(Theme.DIALOGS_DRAFT_TEXT_COLOR), 0,
                        draftString.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                messageString = Emoji.replaceEmoji(stringBuilder, messagePaint.getFontMetricsInt(),
                        AndroidUtilities.dp(20), false);
            }
        } else {
            if (message == null) {
                if (encryptedChat != null) {
                    currentMessagePaint = messagePrintingPaint;
                    if (encryptedChat instanceof TLRPC.TL_encryptedChatRequested) {
                        messageString = LocaleController.getString("EncryptionProcessing",
                                R.string.EncryptionProcessing);
                    } else if (encryptedChat instanceof TLRPC.TL_encryptedChatWaiting) {
                        if (user != null && user.first_name != null) {
                            messageString = LocaleController.formatString("AwaitingEncryption",
                                    R.string.AwaitingEncryption, user.first_name);
                        } else {
                            messageString = LocaleController.formatString("AwaitingEncryption",
                                    R.string.AwaitingEncryption, "");
                        }
                    } else if (encryptedChat instanceof TLRPC.TL_encryptedChatDiscarded) {
                        messageString = LocaleController.getString("EncryptionRejected",
                                R.string.EncryptionRejected);
                    } else if (encryptedChat instanceof TLRPC.TL_encryptedChat) {
                        if (encryptedChat.admin_id == UserConfig.getClientUserId()) {
                            if (user != null && user.first_name != null) {
                                messageString = LocaleController.formatString("EncryptedChatStartedOutgoing",
                                        R.string.EncryptedChatStartedOutgoing, user.first_name);
                            } else {
                                messageString = LocaleController.formatString("EncryptedChatStartedOutgoing",
                                        R.string.EncryptedChatStartedOutgoing, "");
                            }
                        } else {
                            messageString = LocaleController.getString("EncryptedChatStartedIncoming",
                                    R.string.EncryptedChatStartedIncoming);
                        }
                    }
                }
            } else {
                TLRPC.User fromUser = null;
                TLRPC.Chat fromChat = null;
                if (message.isFromUser()) {
                    fromUser = MessagesController.getInstance().getUser(message.messageOwner.from_id);
                } else {
                    fromChat = MessagesController.getInstance().getChat(message.messageOwner.to_id.channel_id);
                }
                if (message.messageOwner instanceof TLRPC.TL_messageService) {
                    messageString = message.messageText;
                    currentMessagePaint = messagePrintingPaint;
                } else {
                    if (chat != null && chat.id > 0 && fromChat == null) {
                        String name;
                        if (message.isOutOwner()) {
                            name = LocaleController.getString("FromYou", R.string.FromYou);
                        } else if (fromUser != null) {
                            name = UserObject.getFirstName(fromUser).replace("\n", "");
                        } else if (fromChat != null) {
                            name = fromChat.title.replace("\n", "");
                        } else {
                            name = "DELETED";
                        }
                        checkMessage = false;
                        SpannableStringBuilder stringBuilder;
                        if (message.caption != null) {
                            String mess = message.caption.toString();
                            if (mess.length() > 150) {
                                mess = mess.substring(0, 150);
                            }
                            stringBuilder = SpannableStringBuilder
                                    .valueOf(String.format("%s: %s", name, mess.replace('\n', ' ')));
                        } else if (message.messageOwner.media != null && !message.isMediaEmpty()) {
                            currentMessagePaint = messagePrintingPaint;
                            if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
                                stringBuilder = SpannableStringBuilder.valueOf(String.format("%s: %s", name,
                                        "\uD83C\uDFAE " + message.messageOwner.media.game.title));
                            } else {
                                stringBuilder = SpannableStringBuilder
                                        .valueOf(String.format("%s: %s", name, message.messageText));
                            }
                            stringBuilder.setSpan(new ForegroundColorSpan(Theme.DIALOGS_ATTACH_TEXT_COLOR),
                                    name.length() + 2, stringBuilder.length(),
                                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        } else if (message.messageOwner.message != null) {
                            String mess = message.messageOwner.message;
                            if (mess.length() > 150) {
                                mess = mess.substring(0, 150);
                            }
                            stringBuilder = SpannableStringBuilder
                                    .valueOf(String.format("%s: %s", name, mess.replace('\n', ' ')));
                        } else {
                            stringBuilder = SpannableStringBuilder.valueOf("");
                        }
                        if (stringBuilder.length() > 0) {
                            stringBuilder.setSpan(new ForegroundColorSpan(Theme.DIALOGS_NAME_TEXT_COLOR), 0,
                                    name.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        }
                        messageString = Emoji.replaceEmoji(stringBuilder, messagePaint.getFontMetricsInt(),
                                AndroidUtilities.dp(20), false);
                    } else {
                        if (message.caption != null) {
                            messageString = message.caption;
                        } else {
                            if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
                                messageString = "\uD83C\uDFAE " + message.messageOwner.media.game.title;
                            } else {
                                messageString = message.messageText;
                            }
                            if (message.messageOwner.media != null && !message.isMediaEmpty()) {
                                currentMessagePaint = messagePrintingPaint;
                            }
                        }
                    }
                }
            }
        }
    }

    if (draftMessage != null) {
        timeString = LocaleController.stringForMessageListDate(draftMessage.date);
    } else if (lastMessageDate != 0) {
        timeString = LocaleController.stringForMessageListDate(lastMessageDate);
    } else if (message != null) {
        timeString = LocaleController.stringForMessageListDate(message.messageOwner.date);
    }

    if (message == null) {
        drawCheck1 = false;
        drawCheck2 = false;
        drawClock = false;
        drawCount = false;
        drawError = false;
    } else {
        if (unreadCount != 0) {
            drawCount = true;
            countString = String.format("%d", unreadCount);
        } else {
            drawCount = false;
        }

        if (message.isOut() && draftMessage == null) {
            if (message.isSending()) {
                drawCheck1 = false;
                drawCheck2 = false;
                drawClock = true;
                drawError = false;
            } else if (message.isSendError()) {
                drawCheck1 = false;
                drawCheck2 = false;
                drawClock = false;
                drawError = true;
                drawCount = false;
            } else if (message.isSent()) {
                drawCheck1 = !message.isUnread() || ChatObject.isChannel(chat) && !chat.megagroup;
                drawCheck2 = true;
                drawClock = false;
                drawError = false;
            }
        } else {
            drawCheck1 = false;
            drawCheck2 = false;
            drawClock = false;
            drawError = false;
        }
    }

    int timeWidth = (int) Math.ceil(timePaint.measureText(timeString));
    timeLayout = new StaticLayout(timeString, timePaint, timeWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f,
            false);
    if (!LocaleController.isRTL) {
        timeLeft = getMeasuredWidth() - AndroidUtilities.dp(15) - timeWidth;
    } else {
        timeLeft = AndroidUtilities.dp(15);
    }

    if (chat != null) {
        nameString = chat.title;
    } else if (user != null) {
        if (user.id == UserConfig.getClientUserId()) {
            nameString = LocaleController.getString("ChatYourSelfName", R.string.ChatYourSelfName);
        } else if (user.id / 1000 != 777 && user.id / 1000 != 333
                && ContactsController.getInstance().contactsDict.get(user.id) == null) {
            if (ContactsController.getInstance().contactsDict.size() == 0
                    && (!ContactsController.getInstance().contactsLoaded
                            || ContactsController.getInstance().isLoadingContacts())) {
                nameString = UserObject.getUserName(user);
            } else {
                if (user.phone != null && user.phone.length() != 0) {
                    nameString = PhoneFormat.getInstance().format("+" + user.phone);
                } else {
                    nameString = UserObject.getUserName(user);
                }
            }
        } else {
            nameString = UserObject.getUserName(user);
        }
        if (encryptedChat != null) {
            currentNamePaint = nameEncryptedPaint;
        }
    }
    if (nameString.length() == 0) {
        nameString = LocaleController.getString("HiddenName", R.string.HiddenName);
    }

    int nameWidth;

    if (!LocaleController.isRTL) {
        nameWidth = getMeasuredWidth() - nameLeft - AndroidUtilities.dp(14) - timeWidth;
    } else {
        nameWidth = getMeasuredWidth() - nameLeft - AndroidUtilities.dp(AndroidUtilities.leftBaseline)
                - timeWidth;
        nameLeft += timeWidth;
    }
    if (drawNameLock) {
        nameWidth -= AndroidUtilities.dp(4) + lockDrawable.getIntrinsicWidth();
    } else if (drawNameGroup) {
        nameWidth -= AndroidUtilities.dp(4) + groupDrawable.getIntrinsicWidth();
    } else if (drawNameBroadcast) {
        nameWidth -= AndroidUtilities.dp(4) + broadcastDrawable.getIntrinsicWidth();
    } else if (drawNameBot) {
        nameWidth -= AndroidUtilities.dp(4) + botDrawable.getIntrinsicWidth();
    }
    if (drawClock) {
        int w = clockDrawable.getIntrinsicWidth() + AndroidUtilities.dp(5);
        nameWidth -= w;
        if (!LocaleController.isRTL) {
            checkDrawLeft = timeLeft - w;
        } else {
            checkDrawLeft = timeLeft + timeWidth + AndroidUtilities.dp(5);
            nameLeft += w;
        }
    } else if (drawCheck2) {
        int w = checkDrawable.getIntrinsicWidth() + AndroidUtilities.dp(5);
        nameWidth -= w;
        if (drawCheck1) {
            nameWidth -= halfCheckDrawable.getIntrinsicWidth() - AndroidUtilities.dp(8);
            if (!LocaleController.isRTL) {
                halfCheckDrawLeft = timeLeft - w;
                checkDrawLeft = halfCheckDrawLeft - AndroidUtilities.dp(5.5f);
            } else {
                checkDrawLeft = timeLeft + timeWidth + AndroidUtilities.dp(5);
                halfCheckDrawLeft = checkDrawLeft + AndroidUtilities.dp(5.5f);
                nameLeft += w + halfCheckDrawable.getIntrinsicWidth() - AndroidUtilities.dp(8);
            }
        } else {
            if (!LocaleController.isRTL) {
                checkDrawLeft = timeLeft - w;
            } else {
                checkDrawLeft = timeLeft + timeWidth + AndroidUtilities.dp(5);
                nameLeft += w;
            }
        }
    }

    if (dialogMuted && !drawVerified) {
        int w = AndroidUtilities.dp(6) + muteDrawable.getIntrinsicWidth();
        nameWidth -= w;
        if (LocaleController.isRTL) {
            nameLeft += w;
        }
    } else if (drawVerified) {
        int w = AndroidUtilities.dp(6) + verifiedDrawable.getIntrinsicWidth();
        nameWidth -= w;
        if (LocaleController.isRTL) {
            nameLeft += w;
        }
    }

    nameWidth = Math.max(AndroidUtilities.dp(12), nameWidth);
    try {
        CharSequence nameStringFinal = TextUtils.ellipsize(nameString.replace('\n', ' '), currentNamePaint,
                nameWidth - AndroidUtilities.dp(12), TextUtils.TruncateAt.END);
        nameLayout = new StaticLayout(nameStringFinal, currentNamePaint, nameWidth,
                Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }

    int messageWidth = getMeasuredWidth() - AndroidUtilities.dp(AndroidUtilities.leftBaseline + 16);
    int avatarLeft;
    if (!LocaleController.isRTL) {
        messageLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline);
        avatarLeft = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 13 : 9);
    } else {
        messageLeft = AndroidUtilities.dp(16);
        avatarLeft = getMeasuredWidth() - AndroidUtilities.dp(AndroidUtilities.isTablet() ? 65 : 61);
    }
    avatarImage.setImageCoords(avatarLeft, avatarTop, AndroidUtilities.dp(52), AndroidUtilities.dp(52));
    if (drawError) {
        int w = errorDrawable.getIntrinsicWidth() + AndroidUtilities.dp(8);
        messageWidth -= w;
        if (!LocaleController.isRTL) {
            errorLeft = getMeasuredWidth() - errorDrawable.getIntrinsicWidth() - AndroidUtilities.dp(11);
        } else {
            errorLeft = AndroidUtilities.dp(11);
            messageLeft += w;
        }
    } else if (countString != null) {
        countWidth = Math.max(AndroidUtilities.dp(12), (int) Math.ceil(countPaint.measureText(countString)));
        countLayout = new StaticLayout(countString, countPaint, countWidth, Layout.Alignment.ALIGN_CENTER, 1.0f,
                0.0f, false);
        int w = countWidth + AndroidUtilities.dp(18);
        messageWidth -= w;
        if (!LocaleController.isRTL) {
            countLeft = getMeasuredWidth() - countWidth - AndroidUtilities.dp(19);
        } else {
            countLeft = AndroidUtilities.dp(19);
            messageLeft += w;
        }
        drawCount = true;
    } else {
        drawCount = false;
    }

    if (checkMessage) {
        if (messageString == null) {
            messageString = "";
        }
        String mess = messageString.toString();
        if (mess.length() > 150) {
            mess = mess.substring(0, 150);
        }
        mess = mess.replace('\n', ' ');
        messageString = Emoji.replaceEmoji(mess, messagePaint.getFontMetricsInt(), AndroidUtilities.dp(17),
                false);
    }
    messageWidth = Math.max(AndroidUtilities.dp(12), messageWidth);
    CharSequence messageStringFinal = TextUtils.ellipsize(messageString, currentMessagePaint,
            messageWidth - AndroidUtilities.dp(12), TextUtils.TruncateAt.END);
    try {
        messageLayout = new StaticLayout(messageStringFinal, currentMessagePaint, messageWidth,
                Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }

    double widthpx;
    float left;
    if (LocaleController.isRTL) {
        if (nameLayout != null && nameLayout.getLineCount() > 0) {
            left = nameLayout.getLineLeft(0);
            widthpx = Math.ceil(nameLayout.getLineWidth(0));
            if (dialogMuted && !drawVerified) {
                nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - AndroidUtilities.dp(6)
                        - muteDrawable.getIntrinsicWidth());
            } else if (drawVerified) {
                nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - AndroidUtilities.dp(6)
                        - verifiedDrawable.getIntrinsicWidth());
            }
            if (left == 0) {
                if (widthpx < nameWidth) {
                    nameLeft += (nameWidth - widthpx);
                }
            }
        }
        if (messageLayout != null && messageLayout.getLineCount() > 0) {
            left = messageLayout.getLineLeft(0);
            if (left == 0) {
                widthpx = Math.ceil(messageLayout.getLineWidth(0));
                if (widthpx < messageWidth) {
                    messageLeft += (messageWidth - widthpx);
                }
            }
        }
    } else {
        if (nameLayout != null && nameLayout.getLineCount() > 0) {
            left = nameLayout.getLineRight(0);
            if (left == nameWidth) {
                widthpx = Math.ceil(nameLayout.getLineWidth(0));
                if (widthpx < nameWidth) {
                    nameLeft -= (nameWidth - widthpx);
                }
            }
            if (dialogMuted || drawVerified) {
                nameMuteLeft = (int) (nameLeft + left + AndroidUtilities.dp(6));
            }
        }
        if (messageLayout != null && messageLayout.getLineCount() > 0) {
            left = messageLayout.getLineRight(0);
            if (left == messageWidth) {
                widthpx = Math.ceil(messageLayout.getLineWidth(0));
                if (widthpx < messageWidth) {
                    messageLeft -= (messageWidth - widthpx);
                }
            }
        }
    }
}

From source file:ayushi.view.fragment.ProductDetailsFragment.java

public void fillProductData() {

    if (!isFromCart) {

        //Fetch and display item from Gloabl Data Model

        itemName.setText(GlobaDataHolder.getGlobaDataHolder().getProductMap().get(subcategoryKey)
                .get(productListNumber).getItemName());

        quanitity.setText(GlobaDataHolder.getGlobaDataHolder().getProductMap().get(subcategoryKey)
                .get(productListNumber).getQuantity());

        itemdescription.setText(GlobaDataHolder.getGlobaDataHolder().getProductMap().get(subcategoryKey)
                .get(productListNumber).getItemDetail());

        String sellCostString = Money.rupees(BigDecimal.valueOf(Long.valueOf(GlobaDataHolder
                .getGlobaDataHolder().getProductMap().get(subcategoryKey).get(productListNumber).getSellMRP())))
                .toString() + "  ";

        String buyMRP = Money.rupees(BigDecimal.valueOf(Long.valueOf(GlobaDataHolder.getGlobaDataHolder()
                .getProductMap().get(subcategoryKey).get(productListNumber).getMRP()))).toString();

        String costString = sellCostString + buyMRP;

        itemSellPrice.setText(costString, BufferType.SPANNABLE);

        Spannable spannable = (Spannable) itemSellPrice.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(GlobaDataHolder.getGlobaDataHolder().getProductMap().get(subcategoryKey)
                        .get(productListNumber).getItemName().charAt(0)),
                mColorGenerator.getColor(GlobaDataHolder.getGlobaDataHolder().getProductMap()
                        .get(subcategoryKey).get(productListNumber).getItemName()));

        Picasso.with(getActivity())/*from  w ww. j av a2  s .c  o m*/
                .load(GlobaDataHolder.getGlobaDataHolder().getProductMap().get(subcategoryKey)
                        .get(productListNumber).getImageURL())
                .placeholder(drawable).error(drawable).fit().centerCrop().networkPolicy(NetworkPolicy.OFFLINE)
                .into(itemImage, new Callback() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onError() {
                        // Try again online if cache failed

                        Picasso.with(getActivity())
                                .load(GlobaDataHolder.getGlobaDataHolder().getProductMap().get(subcategoryKey)
                                        .get(productListNumber).getImageURL())
                                .placeholder(drawable).error(drawable).fit().centerCrop().into(itemImage);
                    }
                });

        LabelView label = new LabelView(getActivity());

        label.setText(GlobaDataHolder.getGlobaDataHolder().getProductMap().get(subcategoryKey)
                .get(productListNumber).getDiscount());
        label.setBackgroundColor(0xffE91E63);

        label.setTargetView(itemImage, 10, LabelView.Gravity.RIGHT_TOP);
    } else {

        //Fetch and display products from Shopping list

        itemName.setText(
                GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(productListNumber).getItemName());

        quanitity.setText(
                GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(productListNumber).getQuantity());

        itemdescription.setText(
                GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(productListNumber).getItemDetail());

        String sellCostString = Money.rupees(BigDecimal.valueOf(Long.valueOf(
                GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(productListNumber).getSellMRP())))
                .toString() + "  ";

        String buyMRP = Money.rupees(BigDecimal.valueOf(Long.valueOf(
                GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(productListNumber).getMRP())))
                .toString();

        String costString = sellCostString + buyMRP;

        itemSellPrice.setText(costString, BufferType.SPANNABLE);

        Spannable spannable = (Spannable) itemSellPrice.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(GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(productListNumber)
                        .getItemName().charAt(0)),
                mColorGenerator.getColor(GlobaDataHolder.getGlobaDataHolder().getShoppingList()
                        .get(productListNumber).getItemName()));

        Picasso.with(getActivity())
                .load(GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(productListNumber)
                        .getImageURL())
                .placeholder(drawable).error(drawable).fit().centerCrop().networkPolicy(NetworkPolicy.OFFLINE)
                .into(itemImage, new Callback() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onError() {
                        // Try again online if cache failed

                        Picasso.with(getActivity())
                                .load(GlobaDataHolder.getGlobaDataHolder().getShoppingList()
                                        .get(productListNumber).getImageURL())
                                .placeholder(drawable).error(drawable).fit().centerCrop().into(itemImage);
                    }
                });

        LabelView label = new LabelView(getActivity());

        label.setText(
                GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(productListNumber).getDiscount());
        label.setBackgroundColor(0xffE91E63);

        label.setTargetView(itemImage, 10, LabelView.Gravity.RIGHT_TOP);

    }
}

From source file:com.andrewshu.android.reddit.threads.ThreadsListActivity.java

public static void fillThreadsListItemView(int position, View view, ThingInfo item, ListActivity activity,
        HttpClient client, RedditSettings settings,
        ThumbnailOnClickListenerFactory thumbnailOnClickListenerFactory) {

    Resources res = activity.getResources();

    TextView titleView = (TextView) view.findViewById(R.id.title);
    TextView votesView = (TextView) view.findViewById(R.id.votes);
    TextView numCommentsSubredditView = (TextView) view.findViewById(R.id.numCommentsSubreddit);
    TextView nsfwView = (TextView) view.findViewById(R.id.nsfw);
    //        TextView submissionTimeView = (TextView) view.findViewById(R.id.submissionTime);
    ImageView voteUpView = (ImageView) view.findViewById(R.id.vote_up_image);
    ImageView voteDownView = (ImageView) view.findViewById(R.id.vote_down_image);
    View thumbnailContainer = view.findViewById(R.id.thumbnail_view);
    FrameLayout thumbnailFrame = (FrameLayout) view.findViewById(R.id.thumbnail_frame);
    ImageView thumbnailImageView = (ImageView) view.findViewById(R.id.thumbnail);
    ProgressBar indeterminateProgressBar = (ProgressBar) view.findViewById(R.id.indeterminate_progress);

    // Set the title and domain using a SpannableStringBuilder
    SpannableStringBuilder builder = new SpannableStringBuilder();
    String title = item.getTitle();
    if (title == null)
        title = "";
    SpannableString titleSS = new SpannableString(title);
    int titleLen = title.length();
    titleSS.setSpan(//from w  w w .  j a  va 2s . c  om
            new TextAppearanceSpan(activity,
                    Util.getTextAppearanceResource(settings.getTheme(), android.R.style.TextAppearance_Large)),
            0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    String domain = item.getDomain();
    if (domain == null)
        domain = "";
    int domainLen = domain.length();
    SpannableString domainSS = new SpannableString("(" + item.getDomain() + ")");
    domainSS.setSpan(
            new TextAppearanceSpan(activity,
                    Util.getTextAppearanceResource(settings.getTheme(), android.R.style.TextAppearance_Small)),
            0, domainLen + 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    if (Util.isLightTheme(settings.getTheme())) {
        if (item.isClicked()) {
            ForegroundColorSpan fcs = new ForegroundColorSpan(res.getColor(R.color.purple));
            titleSS.setSpan(fcs, 0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            ForegroundColorSpan fcs = new ForegroundColorSpan(res.getColor(R.color.blue));
            titleSS.setSpan(fcs, 0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        domainSS.setSpan(new ForegroundColorSpan(res.getColor(R.color.gray_50)), 0, domainLen + 2,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    } else {
        if (item.isClicked()) {
            ForegroundColorSpan fcs = new ForegroundColorSpan(res.getColor(R.color.gray_50));
            titleSS.setSpan(fcs, 0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        domainSS.setSpan(new ForegroundColorSpan(res.getColor(R.color.gray_75)), 0, domainLen + 2,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    builder.append(titleSS).append(" ").append(domainSS);
    titleView.setText(builder);

    votesView.setText("" + item.getScore());
    numCommentsSubredditView.setText(Util.showNumComments(item.getNum_comments()) + "  " + item.getSubreddit());

    if (item.isOver_18()) {
        nsfwView.setVisibility(View.VISIBLE);
    } else {
        nsfwView.setVisibility(View.GONE);
    }

    // Set the up and down arrow colors based on whether user likes
    if (settings.isLoggedIn()) {
        if (item.getLikes() == null) {
            voteUpView.setImageResource(R.drawable.vote_up_gray);
            voteDownView.setImageResource(R.drawable.vote_down_gray);
            votesView.setTextColor(res.getColor(R.color.gray_75));
        } else if (item.getLikes() == true) {
            voteUpView.setImageResource(R.drawable.vote_up_red);
            voteDownView.setImageResource(R.drawable.vote_down_gray);
            votesView.setTextColor(res.getColor(R.color.arrow_red));
        } else {
            voteUpView.setImageResource(R.drawable.vote_up_gray);
            voteDownView.setImageResource(R.drawable.vote_down_blue);
            votesView.setTextColor(res.getColor(R.color.arrow_blue));
        }
    } else {
        voteUpView.setImageResource(R.drawable.vote_up_gray);
        voteDownView.setImageResource(R.drawable.vote_down_gray);
        votesView.setTextColor(res.getColor(R.color.gray_75));
    }

    // Thumbnails open links
    if (thumbnailContainer != null) {
        if (Common.shouldLoadThumbnails(activity, settings)) {
            thumbnailContainer.setVisibility(View.VISIBLE);

            if (item.getUrl() != null) {
                OnClickListener thumbnailOnClickListener = thumbnailOnClickListenerFactory
                        .getThumbnailOnClickListener(item, activity);
                if (thumbnailOnClickListener != null) {
                    thumbnailFrame.setOnClickListener(thumbnailOnClickListener);
                }
            }

            // Show thumbnail based on ThingInfo
            if ("default".equals(item.getThumbnail()) || "self".equals(item.getThumbnail())
                    || StringUtils.isEmpty(item.getThumbnail())) {
                indeterminateProgressBar.setVisibility(View.GONE);
                thumbnailImageView.setVisibility(View.VISIBLE);
                thumbnailImageView.setImageResource(R.drawable.go_arrow);
            } else {
                indeterminateProgressBar.setVisibility(View.GONE);
                thumbnailImageView.setVisibility(View.VISIBLE);
                if (item.getThumbnailBitmap() != null) {
                    thumbnailImageView.setImageBitmap(item.getThumbnailBitmap());
                } else {
                    thumbnailImageView.setImageBitmap(null);
                    new ShowThumbnailsTask(activity, client, R.drawable.go_arrow)
                            .execute(new ThumbnailLoadAction(item, thumbnailImageView, position));
                }
            }

            // Set thumbnail background based on current theme
            if (Util.isLightTheme(settings.getTheme()))
                thumbnailFrame.setBackgroundResource(R.drawable.thumbnail_background_light);
            else
                thumbnailFrame.setBackgroundResource(R.drawable.thumbnail_background_dark);
        } else {
            // if thumbnails disabled, hide thumbnail icon
            thumbnailContainer.setVisibility(View.GONE);
        }
    }
}

From source file:fr.tvbarthel.apps.simpleweatherforcast.MainActivity.java

private void setActionBarAlpha(float alpha) {
    mAlphaForegroundColorSpan.setAlpha(alpha);
    mActionBarSpannableTitle.setSpan(mAlphaForegroundColorSpan, 0, mActionBarSpannableTitle.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    getSupportActionBar().setTitle(mActionBarSpannableTitle);
}

From source file:com.appeaser.sublimepicker.Sampler.java

private SpannableStringBuilder applyBoldStyle(String text) {
    SpannableStringBuilder ss = new SpannableStringBuilder(text);
    ss.setSpan(new StyleSpan(Typeface.BOLD), 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    return ss;/*from w w  w . j  av  a 2  s  .  com*/
}

From source file:android.support.text.emoji.EmojiProcessor.java

private void addEmoji(@NonNull final Spannable spannable, final EmojiMetadata metadata, final int start,
        final int end) {
    final EmojiSpan span = mSpanFactory.createSpan(metadata);
    spannable.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}

From source file:org.kontalk.ui.GroupInfoFragment.java

private void showIdentityDialog(Contact c, boolean subscribed) {
    final String jid = c.getJID();
    final String dialogFingerprint;
    final String fingerprint;
    final boolean selfJid = Authenticator.isSelfJID(getContext(), jid);
    int titleResId = R.string.title_identity;
    String uid;/*from   w  ww . j av  a  2 s . c  o m*/

    PGPPublicKeyRing publicKey = Keyring.getPublicKey(getContext(), jid, MyUsers.Keys.TRUST_UNKNOWN);
    if (publicKey != null) {
        PGPPublicKey pk = PGP.getMasterKey(publicKey);
        String rawFingerprint = PGP.getFingerprint(pk);
        fingerprint = PGP.formatFingerprint(rawFingerprint);

        uid = PGP.getUserId(pk, XmppStringUtils.parseDomain(jid));
        dialogFingerprint = selfJid ? null : rawFingerprint;
    } else {
        // FIXME using another string
        fingerprint = getString(R.string.peer_unknown);
        uid = null;
        dialogFingerprint = null;
    }

    if (Authenticator.isSelfJID(getContext(), jid)) {
        titleResId = R.string.title_identity_self;
    }

    SpannableStringBuilder text = new SpannableStringBuilder();

    if (c.getName() != null && c.getNumber() != null) {
        text.append(c.getName()).append('\n').append(c.getNumber());
    } else {
        int start = text.length();
        text.append(uid != null ? uid : c.getJID());
        text.setSpan(SystemUtils.getTypefaceSpan(Typeface.BOLD), start, text.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    text.append('\n').append(getString(R.string.text_invitation2)).append('\n');

    int start = text.length();
    text.append(fingerprint);
    text.setSpan(SystemUtils.getTypefaceSpan(Typeface.BOLD), start, text.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    int trustStringId;
    CharacterStyle[] trustSpans;

    if (subscribed) {
        int trustedLevel;
        if (c.isKeyChanged()) {
            // the key has changed and was not trusted yet
            trustedLevel = MyUsers.Keys.TRUST_UNKNOWN;
        } else {
            trustedLevel = c.getTrustedLevel();
        }

        switch (trustedLevel) {
        case MyUsers.Keys.TRUST_IGNORED:
            trustStringId = R.string.trust_ignored;
            trustSpans = new CharacterStyle[] { SystemUtils.getTypefaceSpan(Typeface.BOLD),
                    SystemUtils.getColoredSpan(getContext(), R.color.button_danger) };
            break;

        case MyUsers.Keys.TRUST_VERIFIED:
            trustStringId = R.string.trust_verified;
            trustSpans = new CharacterStyle[] { SystemUtils.getTypefaceSpan(Typeface.BOLD),
                    SystemUtils.getColoredSpan(getContext(), R.color.button_success) };
            break;

        case MyUsers.Keys.TRUST_UNKNOWN:
        default:
            trustStringId = R.string.trust_unknown;
            trustSpans = new CharacterStyle[] { SystemUtils.getTypefaceSpan(Typeface.BOLD),
                    SystemUtils.getColoredSpan(getContext(), R.color.button_danger) };
            break;
        }
    } else {
        trustStringId = R.string.status_notsubscribed;
        trustSpans = new CharacterStyle[] { SystemUtils.getTypefaceSpan(Typeface.BOLD), };
    }

    text.append('\n').append(getString(R.string.status_label));
    start = text.length();
    text.append(getString(trustStringId));
    for (CharacterStyle span : trustSpans)
        text.setSpan(span, start, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    MaterialDialog.Builder builder = new MaterialDialog.Builder(getContext()).content(text).title(titleResId);

    if (dialogFingerprint != null && subscribed) {
        builder.onAny(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                switch (which) {
                case POSITIVE:
                    // trust the key
                    trustKey(jid, dialogFingerprint, MyUsers.Keys.TRUST_VERIFIED);
                    break;
                case NEUTRAL:
                    // ignore the key
                    trustKey(jid, dialogFingerprint, MyUsers.Keys.TRUST_IGNORED);
                    break;
                case NEGATIVE:
                    // untrust the key
                    trustKey(jid, dialogFingerprint, MyUsers.Keys.TRUST_UNKNOWN);
                    break;
                }
            }
        }).positiveText(R.string.button_accept).positiveColorRes(R.color.button_success)
                .neutralText(R.string.button_ignore).negativeText(R.string.button_refuse)
                .negativeColorRes(R.color.button_danger);
    } else if (!selfJid) {
        builder.onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                openChat(jid);
            }
        }).positiveText(R.string.button_private_chat);
    }

    builder.show();
}

From source file:org.mariotaku.twidere.view.holder.ActivityTitleSummaryViewHolder.java

private Spanned getTitleStringAboutMe(int stringRes, int stringResMulti, ParcelableUser[] sources) {
    if (sources == null || sources.length == 0)
        return null;
    final Context context = adapter.getContext();
    final boolean nameFirst = adapter.isNameFirst();
    final UserColorNameManager manager = adapter.getUserColorNameManager();
    final Resources resources = context.getResources();
    final Configuration configuration = resources.getConfiguration();
    final SpannableString firstDisplayName = new SpannableString(
            manager.getDisplayName(sources[0], nameFirst, false));
    firstDisplayName.setSpan(new StyleSpan(Typeface.BOLD), 0, firstDisplayName.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    if (sources.length == 1) {
        final String format = context.getString(stringRes);
        return SpanFormatter.format(configuration.locale, format, firstDisplayName);
    } else if (sources.length == 2) {
        final String format = context.getString(stringResMulti);
        final SpannableString secondDisplayName = new SpannableString(
                manager.getDisplayName(sources[1], nameFirst, false));
        secondDisplayName.setSpan(new StyleSpan(Typeface.BOLD), 0, secondDisplayName.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return SpanFormatter.format(configuration.locale, format, firstDisplayName, secondDisplayName);
    } else {//from  w  w  w  .ja v a2 s.  co  m
        final int othersCount = sources.length - 1;
        final SpannableString nOthers = new SpannableString(
                resources.getQuantityString(R.plurals.N_others, othersCount, othersCount));
        nOthers.setSpan(new StyleSpan(Typeface.BOLD), 0, nOthers.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        final String format = context.getString(stringResMulti);
        return SpanFormatter.format(configuration.locale, format, firstDisplayName, nOthers);
    }
}

From source file:fr.tvbarthel.apps.simpleweatherforcast.MainActivity.java

private void setActionBarTitle(int position) {
    String newTitle = getActionBarTitle(position);
    if (mActionBarSpannableTitle == null || !mActionBarSpannableTitle.toString().equals(newTitle)) {
        mActionBarSpannableTitle = new SpannableString(newTitle);
        mActionBarSpannableTitle.setSpan(mTypefaceSpanLight, 0, mActionBarSpannableTitle.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }//from w  ww.  ja va2s .c om
}

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  www.  j av a 2s.  c om*/
    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);
}