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

The following examples show how to use android.text.TextUtils#substring() . 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 check out the related API usage on the sidebar.
Example 1
Source File: BaseInputConnection.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * The default implementation returns the text currently selected, or null if none is
 * selected.
 */
public CharSequence getSelectedText(int flags) {
    final Editable content = getEditable();
    if (content == null) return null;

    int a = Selection.getSelectionStart(content);
    int b = Selection.getSelectionEnd(content);

    if (a > b) {
        int tmp = a;
        a = b;
        b = tmp;
    }

    if (a == b || a < 0) return null;

    if ((flags&GET_TEXT_WITH_STYLES) != 0) {
        return content.subSequence(a, b);
    }
    return TextUtils.substring(content, a, b);
}
 
Example 2
Source File: CreditCardFragment.java    From CreditCardView with MIT License 6 votes vote down vote up
private void applyExpiredDate(CreditCardPaymentMethod creditCardMethod) {
    String value = editExpireCard.getText().toString();
    value = value.replace("/", "");

    String expire = TextUtils.substring(value, 0, 2);

    if (TextUtils.isDigitsOnly(expire)) {
        creditCardMethod.setExpireMonth(Integer.valueOf(expire));
    }

    expire = TextUtils.substring(value, 2, value.length());

    if (TextUtils.isDigitsOnly(expire)) {
        creditCardMethod.setExpireYear(Integer.valueOf(expire));
    }
}
 
Example 3
Source File: AnimatedEditText.java    From AnimatedEditText with Apache License 2.0 5 votes vote down vote up
private String getAnimText() {
    if (TextUtils.isEmpty(mMask)) {
        return TextUtils.substring(getText(), mStart, mEnd);
    } else {
        return TextUtils.substring(getMaskChars(), mStart, mEnd);
    }
}
 
Example 4
Source File: TokenCompleteTextView.java    From SocialTokenAutoComplete with Apache License 2.0 5 votes vote down vote up
protected String currentCompletionText() {
    if (hintVisible) return ""; //Can't have any text if the hint is visible

    Editable editable = getText();
    int end = getSelectionEnd();
    int start = tokenizer.findTokenStart(editable, end);
    if (start < prefix.length()) {
        start = prefix.length();
    }
    return TextUtils.substring(editable, start, end);
}
 
Example 5
Source File: CodenameOneInputConnection.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
boolean extractTextInternal(ExtractedTextRequest request, ExtractedText outText) {

        Component txtCmp = Display.getInstance().getCurrent().getFocused();
        if (txtCmp != null && txtCmp instanceof TextField) {
            String txt = ((TextField) txtCmp).getText();
            int partialStartOffset = -1;
            int partialEndOffset = -1;
            final CharSequence content = txt;
            if (content != null) {
                final int N = content.length();
                outText.partialStartOffset = outText.partialEndOffset = -1;
                partialStartOffset = 0;
                partialEndOffset = N;

                if ((request.flags & InputConnection.GET_TEXT_WITH_STYLES) != 0) {
                    outText.text = content.subSequence(partialStartOffset,
                            partialEndOffset);
                } else {
                    outText.text = TextUtils.substring(content, partialStartOffset,
                            partialEndOffset);
                }

                outText.flags = 0;
                outText.flags |= ExtractedText.FLAG_SINGLE_LINE;
                outText.startOffset = 0;
                outText.selectionStart = Selection.getSelectionStart(content);
                outText.selectionEnd = Selection.getSelectionEnd(content);
                return true;
            }

        }
        return false;
    }
 
Example 6
Source File: RecipientsEditor.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
private static String getFieldAt(String field, Spanned sp, int start, int end,
        Context context) {
    Annotation[] a = sp.getSpans(start, end, Annotation.class);
    String fieldValue = getAnnotation(a, field);
    if (TextUtils.isEmpty(fieldValue)) {
        fieldValue = TextUtils.substring(sp, start, end);
    }
    return fieldValue;

}
 
Example 7
Source File: TokenCompleteTextView.java    From TokenAutoComplete with Apache License 2.0 5 votes vote down vote up
protected String currentCompletionText() {
    if (hintVisible) return ""; //Can't have any text if the hint is visible

    Editable editable = getText();
    Range currentRange = getCurrentCandidateTokenRange();

    String result = TextUtils.substring(editable, currentRange.start, currentRange.end);
    Log.d(TAG, "Current completion text: " + result);
    return result;
}
 
Example 8
Source File: RecipientsEditor.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private static String getFieldAt(String field, Spanned sp, int start, int end,
        Context context) {
    Annotation[] a = sp.getSpans(start, end, Annotation.class);
    String fieldValue = getAnnotation(a, field);
    if (TextUtils.isEmpty(fieldValue)) {
        fieldValue = TextUtils.substring(sp, start, end);
    }
    return fieldValue;

}
 
Example 9
Source File: AnimatedEditText.java    From AnimatedEditText with Apache License 2.0 5 votes vote down vote up
private String getFixedText() {
    if (TextUtils.isEmpty(mMask)) {
        return TextUtils.substring(getText(), 0, mStart);
    } else {
        return TextUtils.substring(getMaskChars(), 0, mStart);
    }
}
 
Example 10
Source File: MultiAutoCompleteTextView.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Performs the text completion by replacing the range from
 * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd} by the
 * the result of passing <code>text</code> through
 * {@link Tokenizer#terminateToken}.
 * In addition, the replaced region will be marked as an AutoText
 * substition so that if the user immediately presses DEL, the
 * completion will be undone.
 * Subclasses may override this method to do some different
 * insertion of the content into the edit box.</p>
 *
 * @param text the selected suggestion in the drop down list
 */
@Override
protected void replaceText(CharSequence text) {
    clearComposingText();

    int end = getSelectionEnd();
    int start = mTokenizer.findTokenStart(getText(), end);

    Editable editable = getText();
    String original = TextUtils.substring(editable, start, end);

    QwertyKeyListener.markAsReplaced(editable, start, end, original);
    editable.replace(start, end, mTokenizer.terminateToken(text));
}
 
Example 11
Source File: TokenCompleteTextView.java    From TokenAutoComplete with Apache License 2.0 5 votes vote down vote up
@Override
protected void replaceText(CharSequence ignore) {
    clearComposingText();

    // Don't build a token for an empty String
    if (selectedObject == null || selectedObject.toString().equals("")) return;

    TokenImageSpan tokenSpan = buildSpanForObject(selectedObject);

    Editable editable = getText();
    Range candidateRange = getCurrentCandidateTokenRange();

    String original = TextUtils.substring(editable, candidateRange.start, candidateRange.end);

    //Keep track of  replacements for a bug workaround
    if (original.length() > 0) {
        lastCompletionText = original;
    }

    if (editable != null) {
        internalEditInProgress = true;
        if (tokenSpan == null) {
            editable.replace(candidateRange.start, candidateRange.end, "");
        } else if (shouldIgnoreToken(tokenSpan.getToken())) {
            editable.replace(candidateRange.start, candidateRange.end, "");
            if (listener != null) {
                listener.onTokenIgnored(tokenSpan.getToken());
            }
        } else {
            SpannableStringBuilder ssb = new SpannableStringBuilder(tokenizer.wrapTokenValue(tokenToString(tokenSpan.token)));
            editable.replace(candidateRange.start, candidateRange.end, ssb);
            editable.setSpan(tokenSpan, candidateRange.start, candidateRange.start + ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            editable.insert(candidateRange.start + ssb.length(), " ");
        }
        internalEditInProgress = false;
    }
}
 
Example 12
Source File: BaseInputConnection.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * The default implementation returns the given amount of text from the
 * current cursor position in the buffer.
 */
public CharSequence getTextBeforeCursor(int length, int flags) {
    final Editable content = getEditable();
    if (content == null) return null;

    int a = Selection.getSelectionStart(content);
    int b = Selection.getSelectionEnd(content);

    if (a > b) {
        int tmp = a;
        a = b;
        b = tmp;
    }

    if (a <= 0) {
        return "";
    }

    if (length > a) {
        length = a;
    }

    if ((flags&GET_TEXT_WITH_STYLES) != 0) {
        return content.subSequence(a - length, a);
    }
    return TextUtils.substring(content, a - length, a);
}
 
Example 13
Source File: RecipientsEditor.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private static String getFieldAt(String field, Spanned sp, int start, int end,
        Context context) {
    Annotation[] a = sp.getSpans(start, end, Annotation.class);
    String fieldValue = getAnnotation(a, field);
    if (TextUtils.isEmpty(fieldValue)) {
        fieldValue = TextUtils.substring(sp, start, end);
    }
    return fieldValue;

}
 
Example 14
Source File: CreditCardPaymentMethod.java    From CreditCardView with MIT License 4 votes vote down vote up
public String getBin() {
    return creditCardNumber != null && creditCardNumber.length() >= BIN_SIZE ?
            TextUtils.substring(creditCardNumber, 0, BIN_SIZE) : null;
}
 
Example 15
Source File: AccessibilityNodeInfoUtils.java    From talkback with Apache License 2.0 4 votes vote down vote up
/**
 * Get text from an accessibility-node, including spans passed from new compat library via Bundle.
 * If span data is invalid, returns text without spans. Each returned ClickableSpanFromBundle
 * should be recycled by caller, but is probably leaked without consequences.
 */
// TODO: Replace with AccessibilityNodeInfoCompat.getText() when it provides spans.
// TODO: When androidx support library is available, change all node.getText() to use
// AccessibilityNodeInfoCompat.getText via this wrapper.

public static CharSequence getText(AccessibilityNodeInfoCompat node) {
  CharSequence nodeText = node.getText();
  if (nodeText == null) {
    return null;
  }

  // Require click action id.
  int actionId = node.getExtras().getInt(SPANS_ACTION_ID_KEY, NO_VALUE);
  if (actionId == NO_VALUE) {
    return nodeText;
  }

  // Require span start indices.
  List<Integer> starts = extrasIntList(node, SPANS_START_KEY);
  if (starts == null || starts.isEmpty()) {
    return nodeText;
  }

  // Get the rest of span data corresponding to each start point.
  List<Integer> ends = extrasIntList(node, SPANS_END_KEY, starts.size());
  List<Integer> flags = extrasIntList(node, SPANS_FLAGS_KEY, starts.size());
  List<Integer> ids = extrasIntList(node, SPANS_ID_KEY, starts.size());
  if (ends == null || flags == null || ids == null) {
    return nodeText;
  }

  // For each span... collect matching data from bundle, into spannable string.
  Spannable spannable = new SpannableString(TextUtils.substring(nodeText, 0, nodeText.length()));
  for (int i = 0; i < starts.size(); i++) {
    ClickableSpanFromBundle span = new ClickableSpanFromBundle(ids.get(i), node, actionId);
    int start = starts.get(i);
    int end = ends.get(i);
    if (end < start) {
      logError("getText", "end=%d < start=%d for i=%d", end, start, i);
      return nodeText;
    }
    spannable.setSpan(span, starts.get(i), ends.get(i), flags.get(i));
  }
  return spannable;
}
 
Example 16
Source File: FeedbackProcessingUtils.java    From talkback with Apache License 2.0 4 votes vote down vote up
/**
 * Splits text contained within the {@link FeedbackItem}'s {@link FeedbackFragment}s into
 * fragments containing less than {@link #MAX_UTTERANCE_LENGTH} characters.
 *
 * @param item The item containing fragments to split.
 */
// Visible for testing
public static void splitLongText(FeedbackItem item) {
  for (int i = 0; i < item.getFragments().size(); ++i) {
    final FeedbackFragment fragment = item.getFragments().get(i);
    final CharSequence fragmentText = fragment.getText();
    if (TextUtils.isEmpty(fragmentText)) {
      continue;
    }

    if (fragmentText.length() >= MAX_UTTERANCE_LENGTH) {
      // If the text from an original fragment exceeds the allowable
      // fragment text length, start by removing the original fragment
      // from the item.
      item.removeFragment(fragment);

      // Split the fragment's text into multiple fragments that don't
      // exceed the limit and add new fragments at the appropriate
      // position in the item.
      final int end = fragmentText.length();
      int start = 0;
      int splitFragments = 0;
      while (start < end) {
        final int fragmentEnd = start + MAX_UTTERANCE_LENGTH - 1;

        // TODO: We currently split only on spaces.
        // Find a better way to do this for languages that don't
        // use spaces.
        int splitLocation = TextUtils.lastIndexOf(fragmentText, ' ', start + 1, fragmentEnd);
        if (splitLocation < 0) {
          splitLocation = Math.min(fragmentEnd, end);
        }
        final CharSequence textSection = TextUtils.substring(fragmentText, start, splitLocation);
        final FeedbackFragment additionalFragment =
            new FeedbackFragment(textSection, fragment.getSpeechParams());
        item.addFragmentAtPosition(additionalFragment, i + splitFragments);
        splitFragments++;
        start = splitLocation;
      }

      // Always replace the metadata from the original fragment on the
      // first fragment resulting from the split
      copyFragmentMetadata(fragment, item.getFragments().get(i));
    }
  }
}
 
Example 17
Source File: TextInputState.java    From 365browser with Apache License 2.0 4 votes vote down vote up
public CharSequence getSelectedText() {
    if (mSelection.start() == mSelection.end()) return null;
    return TextUtils.substring(mText, mSelection.start(), mSelection.end());
}
 
Example 18
Source File: TextInputState.java    From 365browser with Apache License 2.0 4 votes vote down vote up
public CharSequence getTextAfterSelection(int maxChars) {
    return TextUtils.substring(
            mText, mSelection.end(), Math.min(mText.length(), mSelection.end() + maxChars));
}
 
Example 19
Source File: TextInputState.java    From 365browser with Apache License 2.0 4 votes vote down vote up
public CharSequence getTextBeforeSelection(int maxChars) {
    return TextUtils.substring(
            mText, Math.max(0, mSelection.start() - maxChars), mSelection.start());
}