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

The following examples show how to use android.text.TextUtils#substring() . 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 check out the related API usage on the sidebar.
Example 1
/**
 * 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 Project: CreditCardView   File: CreditCardFragment.java    License: 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
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 4
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 5
/**
 * 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 6
@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 7
/**
 * <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 8
private String getFixedText() {
    if (TextUtils.isEmpty(mMask)) {
        return TextUtils.substring(getText(), 0, mStart);
    } else {
        return TextUtils.substring(getMaskChars(), 0, mStart);
    }
}
 
Example 9
private String getAnimText() {
    if (TextUtils.isEmpty(mMask)) {
        return TextUtils.substring(getText(), mStart, mEnd);
    } else {
        return TextUtils.substring(getMaskChars(), mStart, mEnd);
    }
}
 
Example 10
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 11
private void decodequestionItemDataListFromString(List<QuestionItemData> questionItemDataList, String s) {
	QuestionListBean questionListBean = new Gson().fromJson(s,new TypeToken<QuestionListBean>(){}.getType());
	if(questionListBean.state_code !=0){
           afterDataLoaded();
		return ;
	}
	getQuestionDataParams.stateCode = questionListBean.state_code;
	getQuestionDataParams.maxQuestionId =
			Integer.valueOf(questionListBean.getData().getMin_question_id())
			;
	if (getQuestionDataParams.isRefresh) {
		questionItemDataList.clear();
	}

	for (QuestionListBean.DataEntity.QuestionListEntity questionListEntity:
			questionListBean.getData().getQuestion_list()) {
		QuestionItemData questionItemData = new QuestionItemData();
		questionItemData.questionItemType = QuestionItemData.QuestionItemType.TYPE_NORMAL;
		questionItemData.questionItemId = questionListEntity.getQuestion_id();
		questionItemData.questionItemTitle = questionListEntity.getQuestion_title();
		questionItemData.questionItemDetail = questionListEntity.getQuestion_detail()==null?"":questionListEntity.getQuestion_detail();
		questionItemData.questionRaiserUniversity = questionListEntity.getRaiser_university();
		questionItemData.questionRaiserSchool = questionListEntity.getRaiser_subject();
		questionItemData.questionRaiserRealname = questionListEntity.getRaiser_realname();
		questionItemData.questionRaiseTime =questionListEntity.getQuestion_raise_time();
		questionItemData.questionOuterCategory = questionListEntity.getQuestion_outer_category();
		questionItemData.questionInnerCategory = questionListEntity.getQuestion_inner_category();
		questionItemData.questionAnswerNum = String.valueOf(questionListEntity.getQuestion_answer_num()) ;
		questionItemData.questionHotDegree = questionListEntity.getQuestion_hot_degree();
		//questionItemData.questionAbstract = questionListEntity.getQuestion_abstract();
           String detail = FuckBreaker.fuckBreakerAndSpace(questionItemData.questionItemDetail);
		questionItemData.questionAbstract = TextUtils.substring(detail,0,
                   detail.length()<80?detail.length():80);
		questionItemData.questionRaiserHeadImg =questionListEntity.getRaiser_headimg();
		questionItemData.questionTagInJson = questionListEntity.getQuestion_tag_list();
		questionItemData.questionRaiserId = questionListEntity.getQuestion_raiser_id();
		questionItemDataList.add(questionItemData);
	}
       afterDataLoaded();
}
 
Example 12
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 13
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 14
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 15
Source Project: CreditCardView   File: CreditCardPaymentMethod.java    License: 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 16
/**
 * 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 17
/**
 * 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 18
Source Project: 365browser   File: TextInputState.java    License: 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 19
Source Project: 365browser   File: TextInputState.java    License: 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 20
Source Project: 365browser   File: TextInputState.java    License: 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());
}