Example usage for android.text SpannableStringBuilder length

List of usage examples for android.text SpannableStringBuilder length

Introduction

In this page you can find the example usage for android.text SpannableStringBuilder length.

Prototype

public int length() 

Source Link

Document

Return the number of chars in the buffer.

Usage

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

public static ParsedMessage formatMessageText(final Context ctx, final JuickMessage jmsg, boolean condensed) {
    if (jmsg.parsedText != null) {
        return (ParsedMessage) jmsg.parsedText; // was parsed before
    }//ww w . j ava2 s .  co  m
    getColorTheme(ctx);
    SpannableStringBuilder ssb = new SpannableStringBuilder();
    int spanOffset = 0;
    final boolean isMainMessage = jmsg.getRID() == 0;
    final boolean doCompactComment = !isMainMessage && compactComments;
    if (jmsg.continuationInformation != null) {
        ssb.append(jmsg.continuationInformation + "\n");
        ssb.setSpan(new StyleSpan(Typeface.ITALIC), spanOffset, ssb.length() - 1,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    //
    // NAME
    //
    spanOffset = ssb.length();
    String name = '@' + jmsg.User.UName;
    int userNameStart = ssb.length();
    ssb.append(name);
    int userNameEnd = ssb.length();
    StyleSpan userNameBoldSpan;
    ForegroundColorSpan userNameColorSpan;
    ssb.setSpan(userNameBoldSpan = new StyleSpan(Typeface.BOLD), spanOffset, ssb.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    ssb.setSpan(
            userNameColorSpan = new ForegroundColorSpan(
                    colorTheme.getColor(ColorsTheme.ColorKey.USERNAME, 0xFFC8934E)),
            spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    if (helvNueFonts) {
        ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNueBold), spanOffset, ssb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    ssb.append(' ');
    spanOffset = ssb.length();

    if (!condensed) {
        //
        // TAGS
        //
        String tags = jmsg.getTags();
        if (feedlyFonts)
            tags = tags.toUpperCase();
        ssb.append(tags + "\n");
        if (tags.length() > 0) {
            ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.TAGS, 0xFF0000CC)),
                    spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            if (feedlyFonts) {
                ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.dinWebPro), spanOffset,
                        ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else if (helvNueFonts) {
                ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNue), spanOffset,
                        ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

        }
        spanOffset = ssb.length();
    }
    if (jmsg.translated) {
        //
        // 'translated'
        //
        ssb.append("translated: ");
        ssb.setSpan(
                new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.TRANSLATED_LABEL, 0xFF4ec856)),
                spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), spanOffset, ssb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanOffset = ssb.length();
    }
    int bodyOffset = ssb.length();
    int messageNumberStart = -1, messageNumberEnd = -1;
    if (showNumbers(ctx) && !condensed) {
        //
        // numbers
        //
        if (isMainMessage) {
            messageNumberStart = ssb.length();
            ssb.append(jmsg.getDisplayMessageNo());
            messageNumberEnd = ssb.length();
        } else {
            ssb.append("/" + jmsg.getRID());
            if (jmsg.getReplyTo() != 0) {
                ssb.append("->" + jmsg.getReplyTo());
            }
        }
        ssb.append(" ");
        ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.MESSAGE_ID, 0xFFa0a5bd)),
                spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanOffset = ssb.length();
    }
    //
    // MESSAGE BODY
    //
    String txt = Censor.getCensoredText(jmsg.Text);
    if (!condensed) {
        if (jmsg.Photo != null) {
            txt = jmsg.Photo + "\n" + txt;
        }
        if (jmsg.Video != null) {
            txt = jmsg.Video + "\n" + txt;
        }
    }
    ssb.append(txt);
    boolean ssbChanged = false; // allocation optimization
    // Highlight links http://example.com/
    ArrayList<ExtractURLFromMessage.FoundURL> foundURLs = ExtractURLFromMessage.extractUrls(txt, jmsg.getMID());
    ArrayList<String> urls = new ArrayList<String>();
    for (ExtractURLFromMessage.FoundURL foundURL : foundURLs) {
        setSSBSpan(ssb, new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.URLS, 0xFF0000CC)),
                spanOffset + foundURL.start, spanOffset + foundURL.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        urls.add(foundURL.url);
        if (foundURL.title != null) {
            ssb.replace(spanOffset + foundURL.title.start - 1, spanOffset + foundURL.title.start, " ");
            ssb.replace(spanOffset + foundURL.title.end, spanOffset + foundURL.title.end + 1, " ");
            ssb.replace(spanOffset + foundURL.start - 1, spanOffset + foundURL.start, "(");
            ssb.replace(spanOffset + foundURL.end, spanOffset + foundURL.end + 1, ")");
            ssb.setSpan(new StyleSpan(Typeface.BOLD), spanOffset + foundURL.title.start,
                    spanOffset + foundURL.title.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        ssbChanged = true;
    }
    // bold italic underline
    if (jmsg.Text.indexOf("*") != -1) {
        setStyleSpans(ssb, spanOffset, Typeface.BOLD, "*");
        ssbChanged = true;
    }
    if (jmsg.Text.indexOf("/") != 0) {
        setStyleSpans(ssb, spanOffset, Typeface.ITALIC, "/");
        ssbChanged = true;
    }
    if (jmsg.Text.indexOf("_") != 0) {
        setStyleSpans(ssb, spanOffset, UnderlineSpan.class, "_");
        ssbChanged = true;
    }
    if (ssbChanged) {
        txt = ssb.subSequence(spanOffset, ssb.length()).toString(); // ssb was modified in between
    }

    // Highlight nick
    String accountName = XMPPService.getMyAccountName(jmsg.getMID(), ctx);
    if (accountName != null) {
        int scan = spanOffset;
        String nickScanArea = (ssb + " ").toUpperCase();
        while (true) {
            int myNick = nickScanArea.indexOf("@" + accountName.toUpperCase(), scan);
            if (myNick != -1) {
                if (!isNickPart(nickScanArea.charAt(myNick + accountName.length() + 1))) {
                    setSSBSpan(ssb,
                            new BackgroundColorSpan(
                                    colorTheme.getColor(ColorsTheme.ColorKey.USERNAME_ME, 0xFF938e00)),
                            myNick - 1, myNick + accountName.length() + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                scan = myNick + 1;
            } else {
                break;
            }
        }
    }

    // Highlight messages #1234
    int pos = 0;
    Matcher m = getCrossReferenceMsgPattern(jmsg.getMID()).matcher(txt);
    while (m.find(pos)) {
        ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.URLS, 0xFF0000CC)),
                spanOffset + m.start(), spanOffset + m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        pos = m.end();
    }

    SpannableStringBuilder compactDt = null;
    if (!condensed) {

        // found messages count (search results)
        if (jmsg.myFoundCount != 0 || jmsg.hisFoundCount != 0) {
            ssb.append("\n");
            int where = ssb.length();
            if (jmsg.myFoundCount != 0) {
                ssb.append(ctx.getString(R.string.MyReplies_) + jmsg.myFoundCount + "  ");
            }
            if (jmsg.hisFoundCount != 0) {
                ssb.append(ctx.getString(R.string.UserReplies_) + jmsg.hisFoundCount);
            }
            ssb.setSpan(
                    new ForegroundColorSpan(
                            colorTheme.getColor(ColorsTheme.ColorKey.TRANSLATED_LABEL, 0xFF4ec856)),
                    where, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        int rightPartOffset = spanOffset = ssb.length();

        if (!doCompactComment) {
            //
            // TIME (bottom of message)
            //

            try {
                DateFormat df = new SimpleDateFormat("HH:mm dd/MMM/yy");
                String date = jmsg.Timestamp != null ? df.format(jmsg.Timestamp) : "[bad date]";
                if (date.endsWith("/76"))
                    date = date.substring(0, date.length() - 3); // special case for no year in datasource
                ssb.append("\n" + date + " ");
            } catch (Exception e) {
                ssb.append("\n[fmt err] ");
            }

            ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.DATE, 0xFFAAAAAA)),
                    spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            compactDt = new SpannableStringBuilder();
            try {
                if (true || jmsg.deltaTime != Long.MIN_VALUE) {
                    compactDt.append(com.juickadvanced.Utils.toRelaviteDate(jmsg.Timestamp.getTime(), russian));
                } else {
                    DateFormat df = new SimpleDateFormat("HH:mm dd/MMM/yy");
                    String date = jmsg.Timestamp != null ? df.format(jmsg.Timestamp) : "[bad date]";
                    if (date.endsWith("/76"))
                        date = date.substring(0, date.length() - 3); // special case for no year in datasource
                    compactDt.append(date);
                }
            } catch (Exception e) {
                compactDt.append("\n[fmt err] ");
            }
            compactDt.setSpan(
                    new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.DATE, 0xFFAAAAAA)), 0,
                    compactDt.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        }

        spanOffset = ssb.length();

        //
        // Number of REPLIES
        //
        if (jmsg.replies > 0) {
            String replies = Replies + jmsg.replies;
            ssb.append(" " + replies);
            ssb.setSpan(
                    new ForegroundColorSpan(
                            colorTheme.getColor(ColorsTheme.ColorKey.NUMBER_OF_COMMENTS, 0xFFC8934E)),
                    spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            ssb.setSpan(new WrapTogetherSpan() {
            }, spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (!doCompactComment) {
            // right align
            ssb.setSpan(new AlignmentSpan.Standard(Alignment.ALIGN_OPPOSITE), rightPartOffset, ssb.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }

    if (helvNueFonts) {
        ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNue), bodyOffset, ssb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    LeadingMarginSpan.LeadingMarginSpan2 userpicSpan = null;
    if (showUserpics(ctx) && !condensed) {
        userpicSpan = new LeadingMarginSpan.LeadingMarginSpan2() {
            @Override
            public int getLeadingMarginLineCount() {
                if (_wrapUserpics) {
                    return 2;
                } else {
                    return 22222;
                }
            }

            @Override
            public int getLeadingMargin(boolean first) {
                if (first) {
                    return (int) (2 * getLineHeight(ctx, (double) textScale));
                } else {
                    return 0;
                }
            }

            @Override
            public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom,
                    CharSequence text, int start, int end, boolean first, Layout layout) {
            }
        };
        ssb.setSpan(userpicSpan, 0, ssb.length(), 0);
    }
    ParsedMessage parsedMessage = new ParsedMessage(ssb, urls);
    parsedMessage.userpicSpan = userpicSpan;
    parsedMessage.userNameBoldSpan = userNameBoldSpan;
    parsedMessage.userNameColorSpan = userNameColorSpan;
    parsedMessage.userNameStart = userNameStart;
    parsedMessage.userNameEnd = userNameEnd;
    parsedMessage.messageNumberStart = messageNumberStart;
    parsedMessage.messageNumberEnd = messageNumberEnd;
    parsedMessage.compactDate = compactDt;
    return parsedMessage;
}

From source file:com.google.android.apps.location.gps.gnsslogger.PlotFragment.java

/**
 *  Updates the CN0 versus Time plot data from a {@link GnssMeasurement}
 *//*from  ww  w. j  av a2  s.  co  m*/
protected void updateCnoTab(GnssMeasurementsEvent event) {
    long timeInSeconds = TimeUnit.NANOSECONDS.toSeconds(event.getClock().getTimeNanos());
    if (mInitialTimeSeconds < 0) {
        mInitialTimeSeconds = timeInSeconds;
    }

    // Building the texts message in analysis text view
    List<GnssMeasurement> measurements = sortByCarrierToNoiseRatio(new ArrayList<>(event.getMeasurements()));
    SpannableStringBuilder builder = new SpannableStringBuilder();
    double currentAverage = 0;
    if (measurements.size() >= NUMBER_OF_STRONGEST_SATELLITES) {
        mAverageCn0 = (mAverageCn0 * mMeasurementCount
                + (measurements.get(0).getCn0DbHz() + measurements.get(1).getCn0DbHz()
                        + measurements.get(2).getCn0DbHz() + measurements.get(3).getCn0DbHz())
                        / NUMBER_OF_STRONGEST_SATELLITES)
                / (++mMeasurementCount);
        currentAverage = (measurements.get(0).getCn0DbHz() + measurements.get(1).getCn0DbHz()
                + measurements.get(2).getCn0DbHz() + measurements.get(3).getCn0DbHz())
                / NUMBER_OF_STRONGEST_SATELLITES;
    }
    builder.append(getString(R.string.history_average_hint, sDataFormat.format(mAverageCn0) + "\n"));
    builder.append(getString(R.string.current_average_hint, sDataFormat.format(currentAverage) + "\n"));
    for (int i = 0; i < NUMBER_OF_STRONGEST_SATELLITES && i < measurements.size(); i++) {
        int start = builder.length();
        builder.append(mDataSetManager.getConstellationPrefix(measurements.get(i).getConstellationType())
                + measurements.get(i).getSvid() + ": " + sDataFormat.format(measurements.get(i).getCn0DbHz())
                + "\n");
        int end = builder.length();
        builder.setSpan(
                new ForegroundColorSpan(mColorMap.getColor(measurements.get(i).getSvid(),
                        measurements.get(i).getConstellationType())),
                start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }
    builder.append(getString(R.string.satellite_number_sum_hint, measurements.size()));
    mAnalysisView.setText(builder);

    // Adding incoming data into Dataset
    mLastTimeReceivedSeconds = timeInSeconds - mInitialTimeSeconds;
    for (GnssMeasurement measurement : measurements) {
        int constellationType = measurement.getConstellationType();
        int svID = measurement.getSvid();
        if (constellationType != GnssStatus.CONSTELLATION_UNKNOWN) {
            mDataSetManager.addValue(CN0_TAB, constellationType, svID, mLastTimeReceivedSeconds,
                    measurement.getCn0DbHz());
        }
    }

    mDataSetManager.fillInDiscontinuity(CN0_TAB, mLastTimeReceivedSeconds);

    // Checks if the plot has reached the end of frame and resize
    if (mLastTimeReceivedSeconds > mCurrentRenderer.getXAxisMax()) {
        mCurrentRenderer.setXAxisMax(mLastTimeReceivedSeconds);
        mCurrentRenderer.setXAxisMin(mLastTimeReceivedSeconds - TIME_INTERVAL_SECONDS);
    }

    mChartView.invalidate();
}

From source file:com.android.mail.utils.NotificationUtils.java

private static SpannableStringBuilder ellipsizeStyledSenders(final Context context,
        ArrayList<SpannableString> styledSenders) {
    if (sSendersSplitToken == null) {
        sSendersSplitToken = context.getString(R.string.senders_split_token);
        sElidedPaddingToken = context.getString(R.string.elided_padding_token);
    }/* ww w.  ja  v  a  2  s .  c  o  m*/

    SpannableStringBuilder builder = new SpannableStringBuilder();
    SpannableString prevSender = null;
    for (SpannableString sender : styledSenders) {
        if (sender == null) {
            LogUtils.e(LOG_TAG, "null sender iterating over styledSenders");
            continue;
        }
        CharacterStyle[] spans = sender.getSpans(0, sender.length(), CharacterStyle.class);
        if (SendersView.sElidedString.equals(sender.toString())) {
            prevSender = sender;
            sender = copyStyles(spans, sElidedPaddingToken + sender + sElidedPaddingToken);
        } else if (builder.length() > 0
                && (prevSender == null || !SendersView.sElidedString.equals(prevSender.toString()))) {
            prevSender = sender;
            sender = copyStyles(spans, sSendersSplitToken + sender);
        } else {
            prevSender = sender;
        }
        builder.append(sender);
    }
    return builder;
}

From source file:com.heath_bar.tvdb.SeriesOverview.java

private SpannableStringBuilder tagsBuilder(String text, String delim) {
    SpannableStringBuilder builtTags = new SpannableStringBuilder();
    int start = 0;
    int end = 0;//from   ww w .j a v  a 2  s  .  c  o m

    // if no text, break early
    if (text.length() == 0)
        return builtTags;

    // If the string starts with delim, remove the first delim
    if (text.substring(0, 1).equals(delim))
        text = text.substring(1);

    do {
        start = 0;
        end = text.indexOf(delim, 0);

        try {
            if (start < end) {
                final Context ctx = getApplicationContext();
                String targetString = text.substring(start, end);
                SpannableStringBuilder ssb = new SpannableStringBuilder(targetString);
                ssb.setSpan(new NonUnderlinedClickableSpan(targetString) {
                    @Override
                    public void onClick(View v) {
                        Intent myIntent = new Intent(ctx, ActorDetails.class);
                        myIntent.putExtra("ActorName", tag);
                        myIntent.putExtra("seriesId", seriesId);
                        myIntent.putExtra("seriesName", seriesInfo.getName());
                        startActivityForResult(myIntent, 0);
                    }
                }, start, end, 0);
                ssb.setSpan(new TextAppearanceSpan(this, R.style.episode_link), 0, ssb.length(), 0); // Set the style of the text
                //ssb.setSpan(new AbsoluteSizeSpan((int)textSize, true), 0, ssb.length(), 0);            // Override the text size with the user's preference
                builtTags.append(ssb);
                if (text.substring(end + 1).indexOf(delim) >= 0)
                    builtTags.append(", ");
                text = text.substring(end + 1);
            }
        } catch (IndexOutOfBoundsException e) {
        }
    } while (start < end);

    return builtTags;
}

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

protected void runActions() {
    if (!isDialogMode()) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        final CharSequence[] items = new CharSequence[menuActions.size()];
        for (int j = 0; j < items.length; j++) {
            items[j] = menuActions.get(j).title;
        }/*from  w  ww. j  a va  2 s .c om*/
        builder.setItems(items, this);
        final AlertDialog alertDialog = builder.create();
        alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                ColorsTheme.ColorTheme colorTheme = JuickMessagesAdapter.getColorTheme(activity);
                ColorDrawable divider = new ColorDrawable(
                        colorTheme.getColor(ColorsTheme.ColorKey.COMMON_BACKGROUND, 0xFFFFFFFF));
                alertDialog.getListView().setDivider(divider);
                alertDialog.getListView().setDividerHeight(1);
            }
        });
        alertDialog.show();

        final ListAdapter adapter = alertDialog.getListView().getAdapter();
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity);
        float menuFontScale = 1;
        try {
            menuFontScale = Float.parseFloat(sp.getString("menuFontScale", "1.0"));
        } catch (Exception e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
        final boolean compressedMenu = sp.getBoolean("compressedMenu", false);
        final boolean singleLineMenu = sp.getBoolean("singleLineMenu", false);
        final float finalMenuFontScale = menuFontScale;
        final int screenHeight = activity.getWindow().getWindowManager().getDefaultDisplay().getHeight();
        alertDialog.getListView().setAdapter(new ListAdapter() {
            @Override
            public boolean areAllItemsEnabled() {
                return adapter.areAllItemsEnabled();
            }

            @Override
            public boolean isEnabled(int position) {
                return adapter.isEnabled(position);
            }

            @Override
            public void registerDataSetObserver(DataSetObserver observer) {
                adapter.registerDataSetObserver(observer);
            }

            @Override
            public void unregisterDataSetObserver(DataSetObserver observer) {
                adapter.unregisterDataSetObserver(observer);
            }

            @Override
            public int getCount() {
                return items.length;
            }

            @Override
            public Object getItem(int position) {
                return adapter.getItem(position);
            }

            @Override
            public long getItemId(int position) {
                return adapter.getItemId(position);
            }

            @Override
            public boolean hasStableIds() {
                return adapter.hasStableIds();
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View retval = adapter.getView(position, null, parent);
                if (retval instanceof TextView) {
                    TextView tv = (TextView) retval;
                    if (compressedMenu) {
                        int minHeight = (int) ((screenHeight * 0.7) / getCount());
                        tv.setMinHeight(minHeight);
                        tv.setMinimumHeight(minHeight);
                    }
                    if (singleLineMenu) {
                        tv.setSingleLine(true);
                        tv.setEllipsize(TextUtils.TruncateAt.MIDDLE);
                    }
                    tv.setTextSize(22 * finalMenuFontScale);
                }
                return retval;
            }

            @Override
            public int getItemViewType(int position) {
                return adapter.getItemViewType(position);
            }

            @Override
            public int getViewTypeCount() {
                return adapter.getViewTypeCount();
            }

            @Override
            public boolean isEmpty() {
                return adapter.isEmpty();
            }
        });
    } else {
        AlertDialog.Builder builder = new AlertDialog.Builder(
                new ContextThemeWrapper(activity, R.style.Theme_Sherlock));
        View dialogView = activity.getLayoutInflater().inflate(R.layout.message_menu2, null);
        builder.setView(dialogView);
        builder.setCancelable(true);
        int width = activity.getWindowManager().getDefaultDisplay().getWidth();
        View scrollView = dialogView.findViewById(R.id.scrollView);
        scrollView.getLayoutParams().width = (int) (width * 0.90);
        final AlertDialog alertDialog = builder.create();
        alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //MainActivity.restyleChildrenOrWidget(alertDialog.getWindow().getDecorView());
            }
        });
        TextView messageNo = (TextView) dialogView.findViewById(R.id.message_no);
        messageNo.setText(listSelectedItem.getDisplayMessageNo());
        Spinner openUrl = (Spinner) dialogView.findViewById(R.id.open_url);
        Button singleURL = (Button) dialogView.findViewById(R.id.single_url);
        if (urls != null && urls.size() == 1) {
            singleURL.setVisibility(View.VISIBLE);
            openUrl.setVisibility(View.GONE);
            SpannableStringBuilder sb = new SpannableStringBuilder();
            sb.append(urls.get(0));
            sb.setSpan(new UnderlineSpan(), 0, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            singleURL.setText(sb);
            singleURL.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alertDialog.dismiss();
                    launchURL(listSelectedItem.getMID(), urls.get(0));
                }
            });
        } else if (urls != null && urls.size() > 0) {
            singleURL.setVisibility(View.GONE);
            openUrl.setVisibility(View.VISIBLE);
            openUrl.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    if (position != 0) {
                        alertDialog.dismiss();
                        launchURL(listSelectedItem.getMID(), urls.get(position));
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                    //To change body of implemented methods use File | Settings | File Templates.
                }
            });
            urls.add(0, activity.getString(R.string.ClickToSelectURL));
            openUrl.setAdapter(new BaseAdapter() {
                @Override
                public int getCount() {
                    return urls.size();
                }

                @Override
                public Object getItem(int position) {
                    return position;
                }

                @Override
                public long getItemId(int position) {
                    return position;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    View rowView = activity.getLayoutInflater().inflate(android.R.layout.simple_list_item_1,
                            null);
                    TextView textView = (TextView) rowView.findViewById(android.R.id.text1);
                    textView.setSingleLine(false);
                    textView.setMaxLines(5);
                    SpannableStringBuilder sb = new SpannableStringBuilder();
                    sb.append(urls.get(position));
                    if (position == 0) {
                        textView.setTextColor(0xFF808080);
                    } else {
                        sb.setSpan(new UnderlineSpan(), 0, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }
                    textView.setText(sb);
                    return rowView;
                }
            });
        } else {
            openUrl.setVisibility(View.GONE);
            singleURL.setVisibility(View.GONE);
        }
        final String UName = listSelectedItem.User.UName;
        View recommendMessage = dialogView.findViewById(R.id.recommend_message);
        View deleteMessage = dialogView.findViewById(R.id.delete_message);
        View saveMessage = dialogView.findViewById(R.id.save_message);
        View unsaveMessage = dialogView.findViewById(R.id.unsave_message);
        //View subscribeUser = dialogView.findViewById(R.id.subscribe_user);
        View subscribeMessage = dialogView.findViewById(R.id.subscribe_message);
        //View unsubscribeUser = dialogView.findViewById(R.id.unsubscribe_user);
        View unsubscribeMessage = dialogView.findViewById(R.id.unsubscribe_message);
        View translateMessage = dialogView.findViewById(R.id.translate_message);
        View shareMessage = dialogView.findViewById(R.id.share_message);
        //View blacklistUser = dialogView.findViewById(R.id.blacklist_user);
        //View filterUser = dialogView.findViewById(R.id.filter_user);
        //View userBlog = dialogView.findViewById(R.id.user_blog);
        //View userStats = dialogView.findViewById(R.id.user_stats);
        View openMessageInBrowser = dialogView.findViewById(R.id.open_message_in_browser);
        Button userCenter = (Button) dialogView.findViewById(R.id.user_center);
        if (null == dialogView.findViewById(R.id.column_3)) {
            // only for portrait
            userCenter.setText("@" + listSelectedItem.User.UName + " " + userCenter.getText());
        }

        unsubscribeMessage.setEnabled(listSelectedItem.getRID() == 0);
        subscribeMessage.setEnabled(listSelectedItem.getRID() == 0);
        unsaveMessage.setEnabled(listSelectedItem.getRID() == 0);
        recommendMessage.setEnabled(listSelectedItem.getRID() == 0);

        if (UName.equalsIgnoreCase(JuickAPIAuthorizer.getJuickAccountName(activity.getApplicationContext()))) {
            recommendMessage.setVisibility(View.GONE);
        } else {
            deleteMessage.setVisibility(View.GONE);
        }
        if (messagesSource instanceof SavedMessagesSource) {
            saveMessage.setVisibility(View.GONE);
        } else {
            unsaveMessage.setVisibility(View.GONE);
        }
        recommendMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                actionRecommendMessage();
            }
        });
        deleteMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                actionDeleteMessage();
            }
        });
        saveMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                actionSaveMessage();
            }
        });
        unsaveMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                actionUnsaveMessage();
            }
        });
        //            subscribeUser.setOnClickListener(new View.OnClickListener() {
        //                @Override
        //                public void onClick(View v) {
        //                    alertDialog.dismiss();
        //                    actionSubscribeUser();
        //                }
        //            });
        subscribeMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                actionSubscribeMessage();
            }
        });
        //            unsubscribeUser.setOnClickListener(new View.OnClickListener() {
        //                @Override
        //                public void onClick(View v) {
        //                    alertDialog.dismiss();
        //                    actionUnsubscribeUser();
        //                }
        //            });
        unsubscribeMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                actionUnsubscribeMessage();
            }
        });
        translateMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                actionTranslateMessage();
            }
        });
        shareMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                actionShareMessage();
            }
        });
        //            blacklistUser.setOnClickListener(new View.OnClickListener() {
        //                @Override
        //                public void onClick(View v) {
        //                    alertDialog.dismiss();
        //                    actionBlacklistUser();
        //                }
        //            });
        //            filterUser.setOnClickListener(new View.OnClickListener() {
        //                @Override
        //                public void onClick(View v) {
        //                    alertDialog.dismiss();
        //                    actionFilterUser(UName);
        //                }
        //            });
        //            userBlog.setOnClickListener(new View.OnClickListener() {
        //                @Override
        //                public void onClick(View v) {
        //                    alertDialog.dismiss();
        //                    actionUserBlog();
        //                }
        //            });
        //            userStats.setOnClickListener(new View.OnClickListener() {
        //                @Override
        //                public void onClick(View v) {
        //                    alertDialog.dismiss();
        //                    actionUserStats();
        //                }
        //            });
        openMessageInBrowser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                actionOpenMessageInBrowser();
            }
        });
        userCenter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                actionUserCenter();
            }
        });
        completeInitDialogMode(alertDialog, dialogView);
        alertDialog.show();
    }
}

From source file:com.roamprocess1.roaming4world.ui.messages.MessageAdapter.java

private CharSequence formatMessage(String contact, String body, String contentType) {
    System.out.println("MessageAdapter.java in formatMessage() ");
    SpannableStringBuilder buf = new SpannableStringBuilder();
    if (!TextUtils.isEmpty(body)) {
        // Converts html to spannable if ContentType is "text/html".
        if (contentType != null && "text/html".equals(contentType)) {
            buf.append("\n");
            buf.append(Html.fromHtml(body));
        } else {//from  w w  w .jav  a2s. c o m
            SmileyParser parser = SmileyParser.getInstance();
            buf.append(parser.addSmileySpans(body));
        }
    }

    // We always show two lines because the optional icon bottoms are
    // aligned with the
    // bottom of the text field, assuming there are two lines for the
    // message and the sent time.
    buf.append("\n");
    int startOffset = buf.length();
    startOffset = buf.length();
    buf.setSpan(mTextSmallSpan, startOffset, buf.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    System.out.println("formatMessage:" + buf);
    return buf;
}

From source file:com.battlelancer.seriesguide.ui.EpisodeDetailsFragment.java

private void populateEpisodeData(Cursor cursor) {
    if (cursor == null || !cursor.moveToFirst()) {
        // no data to display
        if (mEpisodeContainer != null) {
            mEpisodeContainer.setVisibility(View.GONE);
        }// w ww  .j a va  2s  .c om
        return;
    }

    mShowTvdbId = cursor.getInt(DetailsQuery.REF_SHOW_ID);
    mSeasonNumber = cursor.getInt(DetailsQuery.SEASON);
    mEpisodeNumber = cursor.getInt(DetailsQuery.NUMBER);
    mShowRunTime = cursor.getInt(DetailsQuery.SHOW_RUNTIME);
    mEpisodeReleaseTime = cursor.getLong(DetailsQuery.FIRST_RELEASE_MS);

    // title and description
    mEpisodeTitle = cursor.getString(DetailsQuery.TITLE);
    mTitle.setText(mEpisodeTitle);
    mDescription.setText(cursor.getString(DetailsQuery.OVERVIEW));

    // show title
    mShowTitle = cursor.getString(DetailsQuery.SHOW_TITLE);

    // release time and day
    SpannableStringBuilder timeAndNumbersText = new SpannableStringBuilder();
    if (mEpisodeReleaseTime != -1) {
        Date actualRelease = TimeTools.getEpisodeReleaseTime(getActivity(), mEpisodeReleaseTime);
        mReleaseDay.setText(TimeTools.formatToDate(getActivity(), actualRelease));
        // "in 15 mins (Fri)"
        timeAndNumbersText.append(getString(R.string.release_date_and_day,
                TimeTools.formatToRelativeLocalReleaseTime(getActivity(), actualRelease),
                TimeTools.formatToLocalReleaseDay(actualRelease)).toUpperCase(Locale.getDefault()));
        timeAndNumbersText.append("  ");
    } else {
        mReleaseDay.setText(R.string.unknown);
    }
    // absolute number (e.g. relevant for Anime): "ABSOLUTE 142"
    int numberStartIndex = timeAndNumbersText.length();
    int absoluteNumber = cursor.getInt(DetailsQuery.ABSOLUTE_NUMBER);
    if (absoluteNumber > 0) {
        timeAndNumbersText.append(getString(R.string.episode_number_absolute)).append(" ")
                .append(String.valueOf(absoluteNumber));
        // de-emphasize number
        timeAndNumbersText.setSpan(new TextAppearanceSpan(getActivity(), R.style.TextAppearance_Caption_Dim),
                numberStartIndex, timeAndNumbersText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    mReleaseTime.setText(timeAndNumbersText);

    // guest stars
    Utils.setLabelValueOrHide(mLabelGuestStars, mGuestStars,
            Utils.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.GUESTSTARS)));
    // DVD episode number
    Utils.setLabelValueOrHide(mLabelDvd, mDvd, cursor.getDouble(DetailsQuery.DVDNUMBER));
    // directors
    Utils.setValueOrPlaceholder(mDirectors,
            Utils.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.DIRECTORS)));
    // writers
    Utils.setValueOrPlaceholder(mWriters, Utils.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.WRITERS)));

    // last TVDb edit date
    long lastEditSeconds = cursor.getLong(DetailsQuery.LASTEDIT);
    if (lastEditSeconds > 0) {
        mLastEdit.setText(DateUtils.formatDateTime(getActivity(), lastEditSeconds * 1000,
                DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME));
    } else {
        mLastEdit.setText(R.string.unknown);
    }

    // ratings
    mRatingsContainer.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            rateOnTrakt();
        }
    });
    mRatingsContainer.setFocusable(true);
    CheatSheet.setup(mRatingsContainer, R.string.action_rate);
    // TVDb rating
    String tvdbRating = cursor.getString(DetailsQuery.RATING);
    if (!TextUtils.isEmpty(tvdbRating)) {
        mTvdbRating.setText(tvdbRating);
    }
    // trakt ratings
    loadTraktRatings(true);

    // episode image
    final String imagePath = cursor.getString(DetailsQuery.IMAGE);
    mImageContainer.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent fullscreen = new Intent(getActivity(), FullscreenImageActivity.class);
            fullscreen.putExtra(FullscreenImageActivity.InitBundle.IMAGE_PATH, imagePath);
            ActivityCompat.startActivity(getActivity(), fullscreen, ActivityOptionsCompat
                    .makeScaleUpAnimation(v, 0, 0, v.getWidth(), v.getHeight()).toBundle());
        }
    });
    loadImage(imagePath);

    // check in button
    final int episodeTvdbId = cursor.getInt(DetailsQuery._ID);
    mCheckinButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // display a check-in dialog
            CheckInDialogFragment f = CheckInDialogFragment.newInstance(getActivity(), episodeTvdbId);
            f.show(getFragmentManager(), "checkin-dialog");
            fireTrackerEvent("Check-In");
        }
    });
    CheatSheet.setup(mCheckinButton);

    // watched button
    mEpisodeFlag = cursor.getInt(DetailsQuery.WATCHED);
    boolean isWatched = EpisodeTools.isWatched(mEpisodeFlag);
    Utils.setCompoundDrawablesRelativeWithIntrinsicBounds(mWatchedButton, 0,
            isWatched ? Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableWatched)
                    : Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableWatch),
            0, 0);
    mWatchedButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // disable button, will be re-enabled on data reload once action completes
            v.setEnabled(false);
            onToggleWatched();
            fireTrackerEvent("Toggle watched");
        }
    });
    mWatchedButton.setEnabled(true);
    mWatchedButton.setText(isWatched ? R.string.action_unwatched : R.string.action_watched);
    CheatSheet.setup(mWatchedButton, isWatched ? R.string.action_unwatched : R.string.action_watched);

    // collected button
    mCollected = cursor.getInt(DetailsQuery.COLLECTED) == 1;
    Utils.setCompoundDrawablesRelativeWithIntrinsicBounds(mCollectedButton, 0,
            mCollected ? R.drawable.ic_collected
                    : Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableCollect),
            0, 0);
    mCollectedButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // disable button, will be re-enabled on data reload once action completes
            v.setEnabled(false);
            onToggleCollected();
            fireTrackerEvent("Toggle collected");
        }
    });
    mCollectedButton.setEnabled(true);
    mCollectedButton.setText(mCollected ? R.string.action_collection_remove : R.string.action_collection_add);
    CheatSheet.setup(mCollectedButton,
            mCollected ? R.string.action_collection_remove : R.string.action_collection_add);

    // skip button
    boolean isSkipped = EpisodeTools.isSkipped(mEpisodeFlag);
    if (isWatched) {
        // if watched do not allow skipping
        mSkipButton.setVisibility(View.INVISIBLE);
    } else {
        mSkipButton.setVisibility(View.VISIBLE);
        Utils.setCompoundDrawablesRelativeWithIntrinsicBounds(mSkipButton, 0,
                isSkipped ? R.drawable.ic_skipped
                        : Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableSkip),
                0, 0);
        mSkipButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // disable button, will be re-enabled on data reload once action completes
                v.setEnabled(false);
                onToggleSkipped();
                fireTrackerEvent("Toggle skipped");
            }
        });
        mSkipButton.setText(isSkipped ? R.string.action_dont_skip : R.string.action_skip);
        CheatSheet.setup(mSkipButton, isSkipped ? R.string.action_dont_skip : R.string.action_skip);
    }
    mSkipButton.setEnabled(true);

    // service buttons
    ServiceUtils.setUpTraktButton(mShowTvdbId, mSeasonNumber, mEpisodeNumber, mTraktButton, TAG);
    // IMDb
    String imdbId = cursor.getString(DetailsQuery.IMDBID);
    if (TextUtils.isEmpty(imdbId)) {
        // fall back to show IMDb id
        imdbId = cursor.getString(DetailsQuery.SHOW_IMDBID);
    }
    ServiceUtils.setUpImdbButton(imdbId, mImdbButton, TAG, getActivity());
    // TVDb
    final int seasonTvdbId = cursor.getInt(DetailsQuery.REF_SEASON_ID);
    ServiceUtils.setUpTvdbButton(mShowTvdbId, seasonTvdbId, getEpisodeTvdbId(), mTvdbButton, TAG);
    // trakt comments
    mCommentsButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), TraktShoutsActivity.class);
            intent.putExtras(TraktShoutsActivity.createInitBundleEpisode(mShowTvdbId, mSeasonNumber,
                    mEpisodeNumber, mEpisodeTitle));
            ActivityCompat.startActivity(getActivity(), intent, ActivityOptionsCompat
                    .makeScaleUpAnimation(v, 0, 0, v.getWidth(), v.getHeight()).toBundle());
            fireTrackerEvent("Comments");
        }
    });

    mEpisodeContainer.setVisibility(View.VISIBLE);
}

From source file:cgeo.geocaching.CacheDetailActivity.java

static void appendClickableList(final SpannableStringBuilder builder, final View view, final Integer listId) {
    final int start = builder.length();
    builder.append(DataStore.getList(listId).getTitle());
    builder.setSpan(new ClickableSpan() {
        @Override/*from  ww  w.j ava2s  .  c o  m*/
        public void onClick(final View widget) {
            Settings.setLastDisplayedList(listId);
            CacheListActivity.startActivityOffline(view.getContext());
        }
    }, start, builder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}

From source file:org.telegram.ui.ChannelCreateActivity.java

private ChipSpan createAndPutChipForUser(TLRPC.User user) {
    try {/*from  ww  w  .j  a  v a2  s.  com*/
        LayoutInflater lf = (LayoutInflater) ApplicationLoader.applicationContext
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        View textView = lf.inflate(R.layout.group_create_bubble, null);
        TextView text = (TextView) textView.findViewById(R.id.bubble_text_view);
        String name = UserObject.getUserName(user);
        if (name.length() == 0 && user.phone != null && user.phone.length() != 0) {
            name = PhoneFormat.getInstance().format("+" + user.phone);
        }
        text.setText(name + ", ");

        int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        textView.measure(spec, spec);
        textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight());
        Bitmap b = Bitmap.createBitmap(textView.getWidth(), textView.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(b);
        canvas.translate(-textView.getScrollX(), -textView.getScrollY());
        textView.draw(canvas);
        textView.setDrawingCacheEnabled(true);
        Bitmap cacheBmp = textView.getDrawingCache();
        Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true);
        textView.destroyDrawingCache();

        final BitmapDrawable bmpDrawable = new BitmapDrawable(b);
        bmpDrawable.setBounds(0, 0, b.getWidth(), b.getHeight());

        SpannableStringBuilder ssb = new SpannableStringBuilder("");
        ChipSpan span = new ChipSpan(bmpDrawable, ImageSpan.ALIGN_BASELINE);
        allSpans.add(span);
        selectedContacts.put(user.id, span);
        for (ImageSpan sp : allSpans) {
            ssb.append("<<");
            ssb.setSpan(sp, ssb.length() - 2, ssb.length(), SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        nameTextView.setText(ssb);
        nameTextView.setSelection(ssb.length());
        return span;
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
    return null;
}

From source file:cgeo.geocaching.CacheDetailActivity.java

static void updateCacheLists(final View view, final Geocache cache, final Resources res) {
    final SpannableStringBuilder builder = new SpannableStringBuilder();
    for (final Integer listId : cache.getLists()) {
        if (builder.length() > 0) {
            builder.append(", ");
        }/* w ww  . j  a  va 2  s  .  c o  m*/
        appendClickableList(builder, view, listId);
    }
    builder.insert(0, res.getString(R.string.list_list_headline) + " ");
    final TextView offlineLists = ButterKnife.findById(view, R.id.offline_lists);
    offlineLists.setText(builder);
    offlineLists.setMovementMethod(LinkMovementMethod.getInstance());
}