Java Code Examples for android.text.TextUtils#indexOf()

The following examples show how to use android.text.TextUtils#indexOf() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: imsdk-android   File: RichEditor.java    License: MIT License 6 votes vote down vote up
@Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
    String decode;
    try {
        decode = URLDecoder.decode(url, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // No handling
        return false;
    }

    if (TextUtils.indexOf(url, CALLBACK_SCHEME) == 0) {
        callback(decode);
        return true;
    } else if (TextUtils.indexOf(url, STATE_SCHEME) == 0) {
        stateCheck(decode);
        return true;
    }

    return super.shouldOverrideUrlLoading(view, url);
}
 
Example 2
Source Project: richeditor-android   File: RichEditor.java    License: Apache License 2.0 6 votes vote down vote up
@Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
  String decode;
  try {
    decode = URLDecoder.decode(url, "UTF-8");
  } catch (UnsupportedEncodingException e) {
    // No handling
    return false;
  }

  if (TextUtils.indexOf(url, CALLBACK_SCHEME) == 0) {
    callback(decode);
    return true;
  } else if (TextUtils.indexOf(url, STATE_SCHEME) == 0) {
    stateCheck(decode);
    return true;
  }

  return super.shouldOverrideUrlLoading(view, url);
}
 
Example 3
Source Project: AndroidChromium   File: UrlBar.java    License: Apache License 2.0 5 votes vote down vote up
private void clearAutocompleteSpanIfInvalid() {
    Editable editableText = getEditableText();
    CharSequence previousUserText = mAutocompleteSpan.mUserText;
    CharSequence previousAutocompleteText = mAutocompleteSpan.mAutocompleteText;
    if (editableText.length()
            != (previousUserText.length() + previousAutocompleteText.length())) {
        mAutocompleteSpan.clearSpan();
    } else if (TextUtils.indexOf(getText(), previousUserText) != 0
            || TextUtils.indexOf(getText(),
                    previousAutocompleteText, previousUserText.length()) != 0) {
        mAutocompleteSpan.clearSpan();
    }
}
 
Example 4
public static void removeSeparators(Editable s) {
    int index = TextUtils.indexOf(s, SEPARATOR);
    while (index >= 0) {
        s.delete(index, index + 1);
        index = TextUtils.indexOf(s, SEPARATOR, index + 1);
    }
}
 
Example 5
Source Project: 365browser   File: ChartDataUsageView.java    License: Apache License 2.0 5 votes vote down vote up
private static void setText(
        SpannableStringBuilder builder, Object key, CharSequence text, String bootstrap) {
    int start = builder.getSpanStart(key);
    int end = builder.getSpanEnd(key);
    if (start == -1) {
        start = TextUtils.indexOf(builder, bootstrap);
        end = start + bootstrap.length();
        builder.setSpan(key, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    }
    builder.replace(start, end, text);
}
 
Example 6
Source Project: richeditor-android   File: RichEditor.java    License: Apache License 2.0 5 votes vote down vote up
private void stateCheck(String text) {
  String state = text.replaceFirst(STATE_SCHEME, "").toUpperCase(Locale.ENGLISH);
  List<Type> types = new ArrayList<>();
  for (Type type : Type.values()) {
    if (TextUtils.indexOf(state, type.name()) != -1) {
      types.add(type);
    }
  }

  if (mDecorationStateListener != null) {
    mDecorationStateListener.onStateChangeListener(state, types);
  }
}
 
Example 7
Source Project: HtmlCompat   File: HtmlCompat.java    License: Apache License 2.0 5 votes vote down vote up
private static void withinBlockquoteConsecutive(Context context, StringBuilder out, Spanned text,
                                                int start, int end) {
    out.append("<p").append(getTextDirection(text, start, end)).append(">");
    int next;
    for (int i = start; i < end; i = next) {
        next = TextUtils.indexOf(text, '\n', i, end);
        if (next < 0) {
            next = end;
        }
        int nl = 0;
        while (next < end && text.charAt(next) == '\n') {
            nl++;
            next++;
        }
        withinParagraph(context, out, text, i, next - nl);
        if (nl == 1) {
            out.append("<br>\n");
        } else {
            for (int j = 2; j < nl; j++) {
                out.append("<br>");
            }
            if (next != end) {
                /* Paragraph should be closed and reopened */
                out.append("</p>\n");
                out.append("<p").append(getTextDirection(text, start, end)).append(">");
            }
        }
    }
    out.append("</p>\n");
}
 
Example 8
/**
 * This is a compatibility-method that provides workarounds for several bugs in RxMarkdown
 * <p>
 * https://github.com/stefan-niedermann/nextcloud-notes/issues/772
 *
 * @param markdownProcessor RxMarkdown MarkdownProcessor instance
 * @param text              CharSequence that should be parsed
 * @return the processed text but with several workarounds for Bugs in RxMarkdown
 */
@NonNull
public static CharSequence parseCompat(@NonNull final MarkdownProcessor markdownProcessor, CharSequence text) {
    if (TextUtils.isEmpty(text)) {
        return "";
    }

    while (TextUtils.indexOf(text, MD_IMAGE_WITH_EMPTY_DESCRIPTION) >= 0) {
        text = TextUtils.replace(text, MD_IMAGE_WITH_EMPTY_DESCRIPTION_ARRAY, MD_IMAGE_WITH_SPACE_DESCRIPTION_ARRAY);
    }

    return markdownProcessor.parse(text);
}
 
Example 9
Source Project: decorator-wechat   File: WeChatMessage.java    License: Apache License 2.0 5 votes vote down vote up
static int guessConversationType(final Conversation conversation) {
	final CarExtender.UnreadConversation ext = conversation.ext;
	final String[] messages = ext != null ? ext.getMessages() : null;
	final int num_messages = messages != null ? messages.length : 0;
	final String last_message = num_messages > 0 ? messages[num_messages - 1] : null;
	if (num_messages > 1) {  // Car extender messages with multiple senders are strong evidence for group chat.
		String sender = null;
		for (final String message : messages) {
			final String[] splits = message.split(":", 2);
			if (splits.length < 2) continue;
			if (sender == null) sender = splits[0];
			else if (! sender.equals(splits[0])) return Conversation.TYPE_GROUP_CHAT;   // More than one sender
		}
	}
	final CharSequence content = conversation.summary;
	if (content == null) return Conversation.TYPE_UNKNOWN;
	final String ticker = conversation.ticker.toString().trim();	// Ticker text (may contain trailing spaces) always starts with sender (same as title for direct message, but not for group chat).
	// Content text includes sender for group and service messages, but not for direct messages.
	final int pos = TextUtils.indexOf(content, ticker);             // Seek for the ticker text in content.
	if (pos >= 0 && pos <= 6) {        // Max length (up to 999 unread): [999t]
		// The content without unread count prefix, may or may not start with sender nick
		final CharSequence content_wo_count = pos > 0 && content.charAt(0) == '[' ? content.subSequence(pos, content.length()) : content;
		// content_wo_count.startsWith(title + SENDER_MESSAGE_SEPARATOR)
		if (startsWith(content_wo_count, conversation.title, SENDER_MESSAGE_SEPARATOR)) {   // The title of group chat is group name, not the message sender
			final CharSequence text = content_wo_count.subSequence(
					conversation.title.length() + SENDER_MESSAGE_SEPARATOR.length(), content_wo_count.length());
			if (startWithBracketedPrefixAndOneSpace(last_message, text))      // Ticker: "Bot name: Text", Content: "[2] Bot name: Text", Message: "[Link] Text"
				return Conversation.TYPE_BOT_MESSAGE;
			else if (isBracketedPrefixOnly(last_message)) return Conversation.TYPE_BOT_MESSAGE;
			return Conversation.TYPE_DIRECT_MESSAGE;    // Most probably a direct message with more than 1 unread
		}
		return Conversation.TYPE_GROUP_CHAT;
	} else if (TextUtils.indexOf(ticker, content) >= 0) {
		if (startWithBracketedPrefixAndOneSpace(last_message, content))      // Ticker: "Bot name: Text", Content: "Text", Message: "[Link] Text"
			return Conversation.TYPE_BOT_MESSAGE;
		return Conversation.TYPE_UNKNOWN;				// Indistinguishable (direct message with 1 unread, or a service text message without link)
	} else return Conversation.TYPE_BOT_MESSAGE;		// Most probably a service message with link
}
 
Example 10
Source Project: decorator-wechat   File: WeChatMessage.java    License: Apache License 2.0 5 votes vote down vote up
private static WeChatMessage buildFromCarMessage(final Conversation conversation, final String message, final boolean from_self) {
	String text = message, sender = null;
	final int pos = from_self ? 0 : TextUtils.indexOf(message, SENDER_MESSAGE_SEPARATOR);
	if (pos > 0) {
		sender = message.substring(0, pos);
		final boolean title_as_sender = TextUtils.equals(sender, conversation.title);
		if (conversation.isGroupChat() || title_as_sender) {	// Verify the sender with title for non-group conversation
			text = message.substring(pos + SENDER_MESSAGE_SEPARATOR.length());
			if (conversation.isGroupChat() && title_as_sender) sender = SELF;		// WeChat incorrectly use group chat title as sender for self-sent messages.
		} else sender = null;		// Not really the sender name, revert the parsing result.
	}
	return new WeChatMessage(conversation, from_self ? SELF : sender, EmojiTranslator.translate(text), 0);
}
 
Example 11
Source Project: decorator-wechat   File: SmartReply.java    License: Apache License 2.0 5 votes vote down vote up
static @Nullable CharSequence[] generateChoices(final Message[] messages) {
	if (messages.length == 0) return null;
	final CharSequence text = messages[messages.length - 1].getText();
	final boolean chinese;
	if ((chinese = TextUtils.indexOf(text, '?') >= 0) || TextUtils.indexOf(text, '?') >= 0)
		return REPLIES_FOR_QUESTION[chinese ? 0 : 1];
	return null;
}
 
Example 12
Source Project: YCCustomText   File: WebViewRichEditor.java    License: Apache License 2.0 5 votes vote down vote up
private void stateCheck(String text) {
    String state = text.replaceFirst(STATE_SCHEME, "").toUpperCase(Locale.ENGLISH);
    List<WebRichType> types = new ArrayList<>();
    for (WebRichType type : WebRichType.values()) {
        if (TextUtils.indexOf(state, type.name()) != -1) {
            types.add(type);
        }
    }
    if (mDecorationStateListener != null) {
        mDecorationStateListener.onStateChangeListener(state, types);
    }
}
 
Example 13
private void insertLink() {
    SpannableStringBuilder ssb = new SpannableStringBuilder(editText.getText());
    int start = editText.getText().length();
    int end = start;
    boolean textToFormatIsLink = TextUtils.indexOf(editText.getText().subSequence(start, end), "http") == 0;
    if (textToFormatIsLink) {
        Log.i(TAG, "Inserting link description for position " + start + " to " + end);
        ssb.insert(end, ")");
        ssb.insert(start, "[](");
    } else {
        String clipboardURL = getClipboardURLorNull(editText.getContext());
        if (clipboardURL != null) {
            Log.i(TAG, "Inserting link from clipboard at position " + start + " to " + end + ": " + clipboardURL);
            ssb.insert(end, "](" + clipboardURL + ")");
            end += clipboardURL.length();
        } else {
            Log.i(TAG, "Inserting empty link for position " + start + " to " + end);
            ssb.insert(end, "]()");
        }
        ssb.insert(start, "[");
    }
    end++;
    ssb.setSpan(new StyleSpan(Typeface.NORMAL), start, end, 1);
    editText.setText(ssb);
    if (textToFormatIsLink) {
        editText.setSelection(start + 1);
    } else {
        editText.setSelection(end + 2); // after <end>](
    }
}
 
Example 14
/**
 * Returns a CharSequence that will mirror the contents of the
 * source CharSequence but with the characters in {@link #getOriginal}
 * replaced by ones from {@link #getReplacement}.
 */
public CharSequence getTransformation(CharSequence source, View v) {
    char[] original = getOriginal();
    char[] replacement = getReplacement();

    /*
     * Short circuit for faster display if the text will never change.
     */
    if (!(source instanceof Editable)) {
        /*
         * Check whether the text does not contain any of the
         * source characters so can be used unchanged.
         */
        boolean doNothing = true;
        int n = original.length;
        for (int i = 0; i < n; i++) {
            if (TextUtils.indexOf(source, original[i]) >= 0) {
                doNothing = false;
                break;
            }
        }
        if (doNothing) {
            return source;
        }

        if (!(source instanceof Spannable)) {
            /*
             * The text contains some of the source characters,
             * but they can be flattened out now instead of
             * at display time.
             */
            if (source instanceof Spanned) {
                return new SpannedString(new SpannedReplacementCharSequence(
                                                    (Spanned) source,
                                                    original, replacement));
            } else {
                return new ReplacementCharSequence(source,
                                                   original,
                                                   replacement).toString();
            }
        }
    }

    if (source instanceof Spanned) {
        return new SpannedReplacementCharSequence((Spanned) source,
                                                  original, replacement);
    } else {
        return new ReplacementCharSequence(source, original, replacement);
    }
}
 
Example 15
Source Project: tysq-android   File: Html.java    License: GNU General Public License v3.0 4 votes vote down vote up
private static void withinBlockquoteConsecutive(StringBuilder out, Spanned text, int start,
                                                    int end) {
        out.append("<p").append(getTextDirection(text, start, end)).append(">");

        int next;
        for (int i = start; i < end; i = next) {
            next = TextUtils.indexOf(text, '\n', i, end);
            if (next < 0) {
                next = end;
            }

            int nl = 0;

            while (next < end && text.charAt(next) == '\n') {
                nl++;
                next++;
            }

            withinParagraph(out, text, i, next - nl);

            if (nl == 1) {
                // xxx
//                out.append("<br>\n");
                out.append("<br>");
            } else {
                for (int j = 2; j < nl; j++) {
                    out.append("<br>");
                }
                if (next != end) {
                    /* Paragraph should be closed and reopened */
                    // xxx
//                    out.append("</p>\n");
                    out.append("</p>");
                    out.append("<p").append(getTextDirection(text, start, end)).append(">");
                }
            }
        }
        // xxx
//        out.append("</p>\n");
        out.append("</p>");
    }
 
Example 16
Source Project: FairEmail   File: HtmlEx.java    License: GNU General Public License v3.0 4 votes vote down vote up
private /* static */ void withinBlockquoteIndividual(StringBuilder out, Spanned text, int start,
                                               int end) {
    boolean isInList = false;
    int next;
    for (int i = start; i <= end; i = next) {
        next = TextUtils.indexOf(text, '\n', i, end);
        if (next < 0) {
            next = end;
        }

        if (next == i) {
            if (isInList) {
                // Current paragraph is no longer a list item; close the previously opened list
                isInList = false;
                out.append("</ul>\n");
            }
            out.append("<br>\n");
        } else {
            boolean isListItem = false;
            ParagraphStyle[] paragraphStyles = text.getSpans(i, next, ParagraphStyle.class);
            for (ParagraphStyle paragraphStyle : paragraphStyles) {
                final int spanFlags = text.getSpanFlags(paragraphStyle);
                if ((spanFlags & Spanned.SPAN_PARAGRAPH) == Spanned.SPAN_PARAGRAPH
                        && paragraphStyle instanceof BulletSpan) {
                    isListItem = true;
                    break;
                }
            }

            if (isListItem && !isInList) {
                // Current paragraph is the first item in a list
                isInList = true;
                out.append("<ul")
                        .append(getTextStyles(text, i, next, true, false))
                        .append(">\n");
            }

            if (isInList && !isListItem) {
                // Current paragraph is no longer a list item; close the previously opened list
                isInList = false;
                out.append("</ul>\n");
            }

            String tagType = isListItem ? "li" : "p";
            out.append("<").append(tagType)
                    .append(getTextDirection(text, i, next))
                    .append(getTextStyles(text, i, next, !isListItem, true))
                    .append(">");

            withinParagraph(out, text, i, next);

            out.append("</");
            out.append(tagType);
            out.append(">\n");

            if (next == end && isInList) {
                isInList = false;
                out.append("</ul>\n");
            }
        }

        next++;
    }
}
 
Example 17
public static boolean hasDashOrSpace(final CharSequence s, final int start,
        final int count) {
    return TextUtils.indexOf(s, " ", start, start + count) != -1
            || TextUtils.indexOf(s, "-", start, start + count) != -1;
}
 
Example 18
Source Project: decorator-wechat   File: WeChatMessage.java    License: Apache License 2.0 4 votes vote down vote up
private static WeChatMessage buildFromBasicFields(final Conversation conversation) {
	// Trim the possible trailing white spaces in ticker.
	CharSequence ticker = conversation.ticker;
	int ticker_length = ticker.length();
	int ticker_end = ticker_length;
	while (ticker_end > 0 && ticker.charAt(ticker_end - 1) == ' ') ticker_end--;
	if (ticker_end != ticker_length) {
		ticker = ticker.subSequence(0, ticker_end);
		ticker_length = ticker_end;
	}

	CharSequence sender = null, text;
	int pos = TextUtils.indexOf(ticker, SENDER_MESSAGE_SEPARATOR), unread_count = 0;
	if (pos > 0) {
		sender = ticker.subSequence(0, pos);
		text = ticker.subSequence(pos + SENDER_MESSAGE_SEPARATOR.length(), ticker_length);
	} else text = ticker;

	final CharSequence summary = conversation.summary;
	final int content_length = summary.length();
	CharSequence content_wo_prefix = summary;
	if (content_length > 3 && summary.charAt(0) == '[' && (pos = TextUtils.indexOf(summary, ']', 1)) > 0) {
		unread_count = parsePrefixAsUnreadCount(summary.subSequence(1, pos));
		if (unread_count > 0) {
			conversation.count = unread_count;
			content_wo_prefix = summary.subSequence(pos + 1, content_length);
		} else if (TextUtils.equals(summary.subSequence(pos + 1, content_length), text))
			conversation.setType(Conversation.TYPE_BOT_MESSAGE);	// Only bot message omits prefix (e.g. "[Link]")
	}

	if (sender == null) {	// No sender in ticker, blindly trust the sender in summary text.
		pos = TextUtils.indexOf(content_wo_prefix, SENDER_MESSAGE_SEPARATOR);
		if (pos > 0) {
			sender = content_wo_prefix.subSequence(0, pos);
			text = content_wo_prefix.subSequence(pos + 1, content_wo_prefix.length());
		} else text = content_wo_prefix;
	} else if (! startsWith(content_wo_prefix, sender, SENDER_MESSAGE_SEPARATOR)) {    // Ensure sender matches (in ticker and summary)
		if (unread_count > 0)	// When unread count prefix is present, sender should also be included in summary.
			Log.e(TAG, "Sender mismatch: \"" + sender + "\" in ticker, summary: " + summary.subSequence(0, Math.min(10, content_length)));
		if (startsWith(ticker, sender, SENDER_MESSAGE_SEPARATOR))	// Normal case for single unread message
			return new WeChatMessage(conversation, sender, content_wo_prefix, conversation.timestamp);
	}
	return new WeChatMessage(conversation, sender, text, conversation.timestamp);
}
 
Example 19
Source Project: delion   File: UrlBar.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Autocompletes the text on the url bar and selects the text that was not entered by the
 * user. Using append() instead of setText() to preserve the soft-keyboard layout.
 * @param userText user The text entered by the user.
 * @param inlineAutocompleteText The suggested autocompletion for the user's text.
 */
public void setAutocompleteText(CharSequence userText, CharSequence inlineAutocompleteText) {
    boolean emptyAutocomplete = TextUtils.isEmpty(inlineAutocompleteText);

    if (!emptyAutocomplete) mDisableTextScrollingFromAutocomplete = true;

    int autocompleteIndex = userText.length();

    String previousText = getQueryText();
    CharSequence newText = TextUtils.concat(userText, inlineAutocompleteText);

    setIgnoreTextChangesForAutocomplete(true);
    mDisableTextAccessibilityEvents = true;

    if (!TextUtils.equals(previousText, newText)) {
        // The previous text may also have included autocomplete text, so we only
        // append the new autocomplete text that has changed.
        if (TextUtils.indexOf(newText, previousText) == 0) {
            append(newText.subSequence(previousText.length(), newText.length()));
        } else {
            setUrl(newText.toString(), null);
        }
    }

    if (getSelectionStart() != autocompleteIndex
            || getSelectionEnd() != getText().length()) {
        setSelection(autocompleteIndex, getText().length());

        if (inlineAutocompleteText.length() != 0) {
            // Sending a TYPE_VIEW_TEXT_SELECTION_CHANGED accessibility event causes the
            // previous TYPE_VIEW_TEXT_CHANGED event to be swallowed. As a result the user
            // hears the autocomplete text but *not* the text they typed. Instead we send a
            // TYPE_ANNOUNCEMENT event, which doesn't swallow the text-changed event.
            announceForAccessibility(inlineAutocompleteText);
        }
    }

    if (emptyAutocomplete) {
        mAutocompleteSpan.clearSpan();
    } else {
        mAutocompleteSpan.setSpan(userText, inlineAutocompleteText);
    }

    setIgnoreTextChangesForAutocomplete(false);
    mDisableTextAccessibilityEvents = false;
}
 
Example 20
boolean isChat() { return ticker != null && TextUtils.indexOf(ticker, ':') > 0; }