Example usage for android.text Spannable length

List of usage examples for android.text Spannable length

Introduction

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

Prototype

int length();

Source Link

Document

Returns the length of this character sequence.

Usage

From source file:com.slx.funstream.adapters.ChatAdapter.java

private void linksToImages(Spannable spannable, TextView textView) {
    //      Matcher matcher = Linkify.WEB_URLS.matcher(spannable);
    //      URLSpan[] spans = textView.getUrls();
    URLSpan[] spans = spannable.getSpans(0, spannable.length(), URLSpan.class);
    Log.d(TAG, "URLSpan[] size=" + spans.length);
    for (URLSpan span : spans) {
        String url = span.getURL();
        Log.d(TAG, "START: " + spannable.getSpanStart(span) + "END: " + spannable.getSpanEnd(span) + " " + url);
        ImageTarget t = new ImageTarget(spannable.getSpanStart(span), spannable.getSpanEnd(span), textView,
                spannable);//from   w  ww. ja  va2 s  .  c  o m
        picasso.load(url).resize(300, 300).centerInside().onlyScaleDown().into(t);
        targets.add(t);
    }
}

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

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

    View rowView;/*  www .  j ava 2  s .c o m*/

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}

From source file:com.silentcircle.accounts.AccountStep1.java

private void stripUnderlines(TextView textView) {
    Spannable s = (Spannable) textView.getText();
    URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
    for (URLSpan span : spans) {
        int start = s.getSpanStart(span);
        int end = s.getSpanEnd(span);
        s.removeSpan(span);//from   ww w  . j a  v a2  s. c o  m
        span = new URLSpanNoUnderline(span.getURL());
        s.setSpan(span, start, end, 0);
    }
    textView.setText(s);
}

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

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

    MainActivity.setStatusBar(this);

    toolbarTB.getNavigationIcon().setColorFilter(ContextCompat.getColor(this, MainActivity.primaryTextColor),
            PorterDuff.Mode.SRC_ATOP);// w w w. j  av  a  2  s  .com

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

From source file:com.googlecode.eyesfree.brailleback.BrailleIME.java

private void addMarkingSpan(Spannable spannable, MarkingSpan span, int position) {
    if (position < spannable.length()) {
        spannable.setSpan(span, position, spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }// ww  w  . ja  va2s . c  om
}

From source file:com.taobao.weex.dom.WXTextDomObject.java

protected void updateSpannable(Spannable spannable, int spanFlag) {
    List<SetSpanOperation> ops = createSetSpanOperation(spannable.length(), spanFlag);
    if (mFontSize == UNSET) {
        ops.add(new SetSpanOperation(0, spannable.length(), new AbsoluteSizeSpan(WXText.sDEFAULT_SIZE),
                spanFlag));//from w ww.j  a v a  2  s . c o  m
    }
    Collections.reverse(ops);
    for (SetSpanOperation op : ops) {
        op.execute(spannable);
    }
}

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

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

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

/**
 * Append text in the specified color to the Snackbar.
 *
 * @param message The text to append./*from  w  ww. j a v  a  2s. co m*/
 * @param color   The color to apply to the text.
 * @return This instance.
 */
public SnackbarWrapper appendMessage(CharSequence message, @ColorInt int color) {
    Spannable spannable = new SpannableString(message);
    spannable.setSpan(new ForegroundColorSpan(color), 0, spannable.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    messageView.append(spannable);
    return this;
}

From source file:com.arantius.tivocommander.Explore.java

protected void finishRequest() {
    if (--mRequestCount != 0) {
        return;/*from w w  w  . ja v  a 2  s  . c  om*/
    }

    getParent().setProgressBarIndeterminateVisibility(false);

    if (mRecordingId == null) {
        for (JsonNode recording : mContent.path("recordingForContentId")) {
            String state = recording.path("state").asText();
            if ("inProgress".equals(state) || "complete".equals(state) || "scheduled".equals(state)) {
                mRecordingId = recording.path("recordingId").asText();
                mRecordingState = state;
                break;
            }
        }
    }

    // Fill mChoices based on the data we now have.
    if ("scheduled".equals(mRecordingState)) {
        mChoices.add(RecordActions.DONT_RECORD.toString());
    } else if ("inProgress".equals(mRecordingState)) {
        mChoices.add(RecordActions.RECORD_STOP.toString());
    } else if (mOfferId != null) {
        mChoices.add(RecordActions.RECORD.toString());
    }
    if (mSubscriptionId != null) {
        mChoices.add(RecordActions.SP_MODIFY.toString());
        mChoices.add(RecordActions.SP_CANCEL.toString());
    } else if (mCollectionId != null && !"movie".equals(mContent.path("collectionType").asText())
            && !mContent.has("movieYear")) {
        mChoices.add(RecordActions.SP_ADD.toString());
    }

    setContentView(R.layout.explore);

    // Show only appropriate buttons.
    findViewById(R.id.explore_btn_watch).setVisibility(
            "complete".equals(mRecordingState) || "inprogress".equals(mRecordingState) ? View.VISIBLE
                    : View.GONE);
    hideViewIfNull(R.id.explore_btn_upcoming, mCollectionId);
    if (mChoices.size() == 0) {
        findViewById(R.id.explore_btn_record).setVisibility(View.GONE);
    }
    // Delete / undelete buttons visible only if appropriate.
    findViewById(R.id.explore_btn_delete)
            .setVisibility("complete".equals(mRecordingState) ? View.VISIBLE : View.GONE);
    findViewById(R.id.explore_btn_undelete)
            .setVisibility("deleted".equals(mRecordingState) ? View.VISIBLE : View.GONE);

    // Display titles.
    String title = mContent.path("title").asText();
    String subtitle = mContent.path("subtitle").asText();
    ((TextView) findViewById(R.id.content_title)).setText(title);
    TextView subtitleView = ((TextView) findViewById(R.id.content_subtitle));
    if ("".equals(subtitle)) {
        subtitleView.setVisibility(View.GONE);
    } else {
        subtitleView.setText(subtitle);
    }

    // Display (only the proper) badges.
    if (mRecording != null && mRecording.path("episodic").asBoolean()
            && !mRecording.path("repeat").asBoolean()) {
        findViewById(R.id.badge_new).setVisibility(View.VISIBLE);
    }
    if (mRecording != null && mRecording.path("hdtv").asBoolean()) {
        findViewById(R.id.badge_hd).setVisibility(View.VISIBLE);
    }
    ImageView iconSubType = (ImageView) findViewById(R.id.icon_sub_type);
    TextView textSubType = (TextView) findViewById(R.id.text_sub_type);
    // TODO: Downloading state?
    if ("complete".equals(mRecordingState)) {
        iconSubType.setVisibility(View.GONE);
        textSubType.setVisibility(View.GONE);
    } else if ("inProgress".equals(mRecordingState)) {
        iconSubType.setImageResource(R.drawable.recording_recording);
        textSubType.setText(R.string.sub_recording);
    } else if (mSubscriptionType != null) {
        switch (mSubscriptionType) {
        case SEASON_PASS:
            iconSubType.setImageResource(R.drawable.todo_seasonpass);
            textSubType.setText(R.string.sub_season_pass);
            break;
        case SINGLE_OFFER:
            iconSubType.setImageResource(R.drawable.todo_single_offer);
            textSubType.setText(R.string.sub_single_offer);
            break;
        case WISHLIST:
            iconSubType.setImageResource(R.drawable.todo_wishlist);
            textSubType.setText(R.string.sub_wishlist);
            break;
        default:
            iconSubType.setVisibility(View.GONE);
            textSubType.setVisibility(View.GONE);
        }
    } else {
        iconSubType.setVisibility(View.GONE);
        textSubType.setVisibility(View.GONE);
    }

    // Display channel and time.
    if (mRecording != null) {
        String channelStr = "";
        JsonNode channel = mRecording.path("channel");
        if (!channel.isMissingNode()) {
            channelStr = String.format("%s %s, ", channel.path("channelNumber").asText(),
                    channel.path("callSign").asText());
        }

        // Lots of shows seem to be a few seconds short, add padding so that
        // rounding down works as expected. Magic number.
        final int minutes = (30 + mRecording.path("duration").asInt()) / 60;

        String durationStr = minutes >= 60 ? String.format(Locale.US, "%d hr", minutes / 60)
                : String.format(Locale.US, "%d min", minutes);
        if (isRecordingPartial()) {
            durationStr += " (partial)";
        }
        ((TextView) findViewById(R.id.content_chan_len)).setText(channelStr + durationStr);

        String airTime = new SimpleDateFormat("EEE MMM d, hh:mm a", Locale.US)
                .format(Utils.parseDateTimeStr(mRecording.path("actualStartTime").asText()));
        ((TextView) findViewById(R.id.content_air_time)).setText("Air time: " + airTime);
    } else {
        ((TextView) findViewById(R.id.content_chan_len)).setVisibility(View.GONE);
        ((TextView) findViewById(R.id.content_air_time)).setVisibility(View.GONE);
    }

    // Construct and display details.
    ArrayList<String> detailParts = new ArrayList<String>();
    int season = mContent.path("seasonNumber").asInt();
    int epNum = mContent.path("episodeNum").path(0).asInt();
    if (season != 0 && epNum != 0) {
        detailParts.add(String.format("Sea %d Ep %d", season, epNum));
    }
    if (mContent.has("mpaaRating")) {
        detailParts.add(mContent.path("mpaaRating").asText().toUpperCase(Locale.US));
    } else if (mContent.has("tvRating")) {
        detailParts.add("TV-" + mContent.path("tvRating").asText().toUpperCase(Locale.US));
    }
    detailParts.add(mContent.path("category").path(0).path("label").asText());
    int year = mContent.path("originalAirYear").asInt();
    if (year != 0) {
        detailParts.add(Integer.toString(year));
    }

    // Filter empty strings.
    for (int i = detailParts.size() - 1; i >= 0; i--) {
        if ("".equals(detailParts.get(i)) || null == detailParts.get(i)) {
            detailParts.remove(i);
        }
    }
    // Then format the parts into one string.
    String detail1 = "(" + Utils.join(", ", detailParts) + ") ";
    if ("() ".equals(detail1)) {
        detail1 = "";
    }

    String detail2 = mContent.path("description").asText();
    TextView detailView = ((TextView) findViewById(R.id.content_details));
    if (detail2 == null) {
        detailView.setText(detail1);
    } else {
        Spannable details = new SpannableString(detail1 + detail2);
        details.setSpan(new ForegroundColorSpan(Color.WHITE), detail1.length(), details.length(), 0);
        detailView.setText(details);
    }

    // Add credits.
    ArrayList<String> credits = new ArrayList<String>();
    for (JsonNode credit : mContent.path("credit")) {
        String role = credit.path("role").asText();
        if ("actor".equals(role) || "host".equals(role) || "guestStar".equals(role)) {
            credits.add(credit.path("first").asText() + " " + credit.path("last").asText());
        }
    }
    TextView creditsView = (TextView) findViewById(R.id.content_credits);
    creditsView.setText(Utils.join(", ", credits));

    // Find and set the banner image if possible.
    ImageView imageView = (ImageView) findViewById(R.id.content_image);
    View progressView = findViewById(R.id.content_image_progress);
    String imageUrl = Utils.findImageUrl(mContent);
    new DownloadImageTask(this, imageView, progressView).execute(imageUrl);
}

From source file:com.cw.litenote.note.Note_adapter.java

private String getHtmlStringWithViewPort(int position, int viewPort) {
    int mStyle = Note.mStyle;

    System.out.println("Note_adapter / _getHtmlStringWithViewPort");
    String strTitle = db_page.getNoteTitle(position, true);
    String strBody = db_page.getNoteBody(position, true);
    String linkUri = db_page.getNoteLinkUri(position, true);

    // replace note title
    //TitleBody,YouTube linkWeb linkTitlelinktitle,Gray?
    boolean bSetGray = false;
    if (Util.isEmptyString(strTitle) && Util.isEmptyString(strBody)) {
        if (Util.isYouTubeLink(linkUri)) {
            strTitle = Util.getYouTubeTitle(linkUri);
            bSetGray = true;/*w  w  w .  j  a  v  a  2 s .com*/
        } else if (linkUri.startsWith("http")) {
            strTitle = mWebTitle;
            bSetGray = true;
        }
    }

    Long createTime = db_page.getNoteCreatedTime(position, true);
    String head = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<html><head>"
            + "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />";

    if (viewPort == VIEW_PORT_BY_NONE) {
        head = head + "<head>";
    } else if (viewPort == VIEW_PORT_BY_DEVICE_WIDTH) {
        head = head + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" + "<head>";
    } else if (viewPort == VIEW_PORT_BY_SCREEN_WIDTH) {
        //           int screen_width = UtilImage.getScreenWidth(act);
        int screen_width = 640;
        head = head + "<meta name=\"viewport\" content=\"width=" + String.valueOf(screen_width)
                + ", initial-scale=1\">" + "<head>";
    }

    String separatedLineTitle = (!Util.isEmptyString(strTitle)) ? "<hr size=2 color=blue width=99% >" : "";
    String separatedLineBody = (!Util.isEmptyString(strBody)) ? "<hr size=1 color=black width=99% >" : "";

    // title
    if (!Util.isEmptyString(strTitle)) {
        Spannable spanTitle = new SpannableString(strTitle);
        Linkify.addLinks(spanTitle, Linkify.ALL);
        spanTitle.setSpan(new AlignmentSpan.Standard(Alignment.ALIGN_CENTER), 0, spanTitle.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        //ref http://stackoverflow.com/questions/3282940/set-color-of-textview-span-in-android
        if (bSetGray) {
            ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.GRAY);
            spanTitle.setSpan(foregroundSpan, 0, spanTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        strTitle = Html.toHtml(spanTitle);
    } else
        strTitle = "";

    // body
    if (!Util.isEmptyString(strBody)) {
        Spannable spanBody = new SpannableString(strBody);
        Linkify.addLinks(spanBody, Linkify.ALL);
        strBody = Html.toHtml(spanBody);
    } else
        strBody = "";

    // set web view text color
    String colorStr = Integer.toHexString(ColorSet.mText_ColorArray[mStyle]);
    colorStr = colorStr.substring(2);

    String bgColorStr = Integer.toHexString(ColorSet.mBG_ColorArray[mStyle]);
    bgColorStr = bgColorStr.substring(2);

    return head + "<body color=\"" + bgColorStr + "\">" + "<br>" + //Note: text mode needs this, otherwise title is overlaid
            "<p align=\"center\"><b>" + "<font color=\"" + colorStr + "\">" + strTitle + "</font>" + "</b></p>"
            + separatedLineTitle + "<p>" + "<font color=\"" + colorStr + "\">" + strBody + "</font>" + "</p>"
            + separatedLineBody + "<p align=\"right\">" + "<font color=\"" + colorStr + "\">"
            + Util.getTimeString(createTime) + "</font>" + "</p>" + "</body></html>";
}