Java Code Examples for android.text.Editable#delete()

The following examples show how to use android.text.Editable#delete() . 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: SettingTextWatcher.java    From AirFree-Client with GNU General Public License v3.0 7 votes vote down vote up
@Override
	public void afterTextChanged(Editable s) {
		if (TextUtils.isEmpty(s)) {
			return;
		}
		String content = s.toString();
//		Log.e("demo", "content:"+content);
		if (isNumeric(content)) {
			int num = Integer.parseInt(content);
			if (num > maxValue || num < minValue) {
				s.delete(editStart, editStart+editCount);
				mEditTextPreference.getEditText().setText(s);
				Toast.makeText(mContext, "超出有效值范围", Toast.LENGTH_SHORT).show();
			}
		}else {
			s.delete(editStart, editStart+editCount);
			mEditTextPreference.getEditText().setText(s);
			Toast.makeText(mContext, "只能输入数字哦", Toast.LENGTH_SHORT).show();
		}
	}
 
Example 2
Source File: ConverterHtmlToText.java    From memoir with Apache License 2.0 6 votes vote down vote up
/**
 * When we come upon an ignored tag, we mark it with an Annotation object with a specific key
 * and value as above. We don't really need to be checking these values since Html.fromHtml()
 * doesn't use Annotation spans, but we should do it now to be safe in case they do start using
 * it in the future.
 *
 * @param opening If this is an opening tag or not.
 * @param output  Spannable string that we're working with.
 */
private void handleIgnoredTag(boolean opening, Editable output) {
    int len = output.length();
    if (opening) {
        output.setSpan(new Annotation(IGNORED_ANNOTATION_KEY, IGNORED_ANNOTATION_VALUE), len,
                len, Spanned.SPAN_MARK_MARK);
    } else {
        Object start = getOpeningAnnotation(output);
        if (start != null) {
            int where = output.getSpanStart(start);
            // Remove the temporary Annotation span.
            output.removeSpan(start);
            // Delete everything between the start of the Annotation and the end of the string
            // (what we've generated so far).
            output.delete(where, len);
        }
    }
}
 
Example 3
Source File: TokenCompleteTextView.java    From TokenAutoComplete with Apache License 2.0 6 votes vote down vote up
/**
 * Remove a span from the current EditText and fire the appropriate callback
 *
 * @param text Editable to remove the span from
 * @param span TokenImageSpan to be removed
 */
private void removeSpan(Editable text, TokenImageSpan span) {
    //We usually add whitespace after a token, so let's try to remove it as well if it's present
    int end = text.getSpanEnd(span);
    if (end < text.length() && text.charAt(end) == ' ') {
        end += 1;
    }

    internalEditInProgress = true;
    text.delete(text.getSpanStart(span), end);
    internalEditInProgress = false;

    if (allowCollapse && !isFocused()) {
        updateCountSpan();
    }
}
 
Example 4
Source File: RichEditText.java    From RichEditText with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param bitmap
 * @param filePath
 * @param start
 * @param end
 */
public void addImage(Bitmap bitmap, String filePath,int start,int end) {
	Log.i("imgpath", filePath);
	String pathTag = "<img src=\"" + filePath + "\"/>";
	SpannableString spanString = new SpannableString(pathTag);
	// 获取屏幕的宽高
	int paddingLeft = getPaddingLeft();
	int paddingRight = getPaddingRight();
	int bmWidth = bitmap.getWidth();//图片高度
	int bmHeight = bitmap.getHeight();//图片宽度
	int zoomWidth =  getWidth() - (paddingLeft + paddingRight);
	int zoomHeight = (int) (((float)zoomWidth / (float)bmWidth) * bmHeight);
	Bitmap newBitmap = zoomImage(bitmap, zoomWidth,zoomHeight);
	ImageSpan imgSpan = new ImageSpan(mContext, newBitmap);
	spanString.setSpan(imgSpan, 0, pathTag.length(),
			Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
	Editable editable = this.getText(); // 获取edittext内容
	editable.delete(start, end);//删除
	editable.insert(start, spanString); // 设置spanString要添加的位置
}
 
Example 5
Source File: RecipientEditTextView.java    From talk-android with MIT License 6 votes vote down vote up
/**
 * Remove the chip and any text associated with it from the RecipientEditTextView.
 */
// Visible for testing.
/* package */void removeChip(DrawableRecipientChip chip) {
    Spannable spannable = getSpannable();
    int spanStart = spannable.getSpanStart(chip);
    int spanEnd = spannable.getSpanEnd(chip);
    Editable text = getText();
    int toDelete = spanEnd;
    boolean wasSelected = chip == mSelectedChip;
    // Clear that there is a selected chip before updating any text.
    if (wasSelected) {
        mSelectedChip = null;
    }
    // Always remove trailing spaces when removing a chip.
    while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
        toDelete++;
    }
    spannable.removeSpan(chip);
    if (spanStart >= 0 && toDelete > 0) {
        text.delete(spanStart, toDelete);
    }
    if (wasSelected) {
        clearSelectedChip();
    }
}
 
Example 6
Source File: KeyboardDelegater.java    From libcommon with Apache License 2.0 6 votes vote down vote up
@Override
public void onKey(final int primaryCode, final int[] keyCodes) {
	if (DEBUG) Log.v(TAG, "onKey:primaryCode=" + primaryCode);
	Editable editable = mEditText.getText();
	int start = mEditText.getSelectionStart();
	if (primaryCode == Keyboard.KEYCODE_DELETE) {
		// 削除(Delete)キー
		if (editable != null && editable.length() > 0) {
			if (start > 0) {
				editable.delete(start - 1, start);
			}
		}
	} else if (primaryCode == Keyboard.KEYCODE_CANCEL) {
		// キャンセル(ESC)キー
		hideKeyboard();
		onCancelClick();
	} else if (primaryCode == Keyboard.KEYCODE_DONE) {
		// 完了(ENTER)キー
		hideKeyboard();
		onOkClick();
	} else {
		// それ以外のキー入力
		editable.insert(start, Character.toString((char) primaryCode));
	}
}
 
Example 7
Source File: FeedEditText.java    From umeng_community_android with MIT License 6 votes vote down vote up
/**
 * @param start
 * @param text
 */
public void deleteElement(int start, String text) {
    Editable editableText = getText();
    // +1表示每个话题或者好友name后的一个空格
    final int deleteLength = text.length() + 1;
    if (start + deleteLength > this.length()) {
        Log.d(VIEW_LOG_TAG, "### 删除的文字超过了原来的长度");
        return;
    }

    isDecorating = true;

    // 删除这个区域的文本
    Editable newEditable = editableText.delete(start,
            start + deleteLength);
    setText(newEditable);

    // 更新索引
    updateMapIndex(start, -deleteLength);
    isDecorating = false;
    mCursorIndex = newEditable.length();
    setSelection(mCursorIndex);
}
 
Example 8
Source File: ConverterHtmlToText.java    From memoir with Apache License 2.0 6 votes vote down vote up
/**
 * When we come upon an ignored tag, we mark it with an Annotation object with a specific key
 * and value as above. We don't really need to be checking these values since Html.fromHtml()
 * doesn't use Annotation spans, but we should do it now to be safe in case they do start using
 * it in the future.
 *
 * @param opening If this is an opening tag or not.
 * @param output  Spannable string that we're working with.
 */
private void handleIgnoredTag(boolean opening, Editable output) {
    int len = output.length();
    if (opening) {
        output.setSpan(new Annotation(IGNORED_ANNOTATION_KEY, IGNORED_ANNOTATION_VALUE), len,
                len, Spanned.SPAN_MARK_MARK);
    } else {
        Object start = getOpeningAnnotation(output);
        if (start != null) {
            int where = output.getSpanStart(start);
            // Remove the temporary Annotation span.
            output.removeSpan(start);
            // Delete everything between the start of the Annotation and the end of the string
            // (what we've generated so far).
            output.delete(where, len);
        }
    }
}
 
Example 9
Source File: TroopSelectActivity.java    From QNotified with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void afterTextChanged(Editable s) {
    String str = s.toString();
    int i = str.indexOf('\n');
    if (i != -1) {
        s.delete(i, i + 1);
    }
    str = s.toString();
    if (s.length() == 0) return;
    searchMode = true;
    parseKeyword(str);
}
 
Example 10
Source File: TokenCompleteTextView.java    From SocialTokenAutoComplete with Apache License 2.0 5 votes vote down vote up
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    System.out.println("changing text: " + s);
    Editable text = getText();
    if (text == null)
        return;

    clearSelections();
    updateHint();

    TokenImageSpan[] spans = text.getSpans(start - before, start - before + count, TokenImageSpan.class);

    for (TokenImageSpan token: spans) {

        int position = start + count;
        if (text.getSpanStart(token) < position && position <= text.getSpanEnd(token)) {
            //We may have to manually reverse the auto-complete and remove the extra ,'s
            int spanStart = text.getSpanStart(token);
            int spanEnd = text.getSpanEnd(token);

            removeToken(token, text);

            //The end of the span is the character index after it
            spanEnd--;

            if (spanEnd >= 0 && text.charAt(spanEnd) == SPLITOR) {
                text.delete(spanEnd, spanEnd + 1);
            }

            if (spanStart > 0 && text.charAt(spanStart) == SPLITOR) {
                text.delete(spanStart, spanStart + 1);
            }
        }
    }
}
 
Example 11
Source File: JotaTextKeyListener.java    From PowerFileExplorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Performs the action that happens when you press the DEL key in
 * a TextView.  If there is a selection, deletes the selection;
 * otherwise, DEL alone deletes the character before the cursor,
 * if any;
 * ALT+DEL deletes everything on the line the cursor is on.
 *
 * @return true if anything was deleted; false otherwise.
 */
public boolean forwardDelete(View view, Editable content, int keyCode,
                         KeyEvent event) {
    int selStart, selEnd;
    boolean result = true;

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

        selStart = Math.min(a, b);
        selEnd = Math.max(a, b);
    }

    if (selStart != selEnd) {
        content.delete(selStart, selEnd);
    } else {
        int to = TextUtils.getOffsetAfter(content, selEnd);

        if (to != selEnd) {
            content.delete(Math.min(to, selEnd), Math.max(to, selEnd));
        }
        else {
            result = false;
        }
    }

    if (result)
        adjustMetaAfterKeypress(content);

    return result;
}
 
Example 12
Source File: ColorChooser.java    From SuntimesWidget with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void afterTextChanged(Editable editable)
{
    if (isRunning || isRemoving)
        return;
    isRunning = true;

    String text = editable.toString();             // should consist of [#][0-9][a-f]
    for (int j=text.length()-1; j>=0; j--)
    {
        if (!inputSet.contains(text.charAt(j)))
        {
            editable.delete(j, j+1);
        }
    }

    text = editable.toString();                   // should start with a #
    int i = text.indexOf('#');
    if (i != -1)
    {
        editable.delete(i, i + 1);
    }
    editable.insert(0, "#");

    if (editable.length() > 8)                   // should be no longer than 8
    {
        editable.delete(9, editable.length());
    }

    text = editable.toString();
    String toCaps = text.toUpperCase(Locale.US);
    editable.clear();
    editable.append(toCaps);

    isRunning = false;
}
 
Example 13
Source File: RTManager.java    From memoir with Apache License 2.0 5 votes vote down vote up
private void insertImage(final RTEditText editor, final RTImage image) {
    if (image != null && editor != null) {
        Selection selection = new Selection(editor);
        Editable str = editor.getText();

        // Unicode Character 'OBJECT REPLACEMENT CHARACTER' (U+FFFC)
        // see http://www.fileformat.info/info/unicode/char/fffc/index.htm
        str.insert(selection.start(), "\uFFFC");

        try {
            // now add the actual image and inform the RTOperationManager about the operation
            Spannable oldSpannable = editor.cloneSpannable();

            ImageSpan imageSpan = new ImageSpan(image, false);
            str.setSpan(imageSpan, selection.start(), selection.end() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            int selStartAfter = editor.getSelectionStart();
            int selEndAfter = editor.getSelectionEnd();
            editor.onAddMedia(image);

            Spannable newSpannable = editor.cloneSpannable();

            mOPManager.executed(editor, new RTOperationManager.TextChangeOperation(oldSpannable, newSpannable,
                    selection.start(), selection.end(), selStartAfter, selEndAfter));
        } catch (OutOfMemoryError e) {
            str.delete(selection.start(), selection.end() + 1);
            mRTApi.makeText(R.string.rte_add_image_error, Toast.LENGTH_LONG).show();
        }
    }
}
 
Example 14
Source File: MeFeedbackAty.java    From myapplication with Apache License 2.0 5 votes vote down vote up
@Override
public void afterTextChanged(Editable s) {
    int number = maxLength - s.length();
    feedbackHasNumTv.setText("" + number);
    editStart = feedbackEt.getSelectionStart();
    editEnd = feedbackEt.getSelectionEnd();

    if (charSequence.length() > maxLength) {
        s.delete(editStart - 1, editEnd);
        int tempSelection = editEnd;
        feedbackEt.setText(s);
        feedbackEt.setSelection(tempSelection);
    }
}
 
Example 15
Source File: CommonEditDialog.java    From AssistantBySDK with Apache License 2.0 5 votes vote down vote up
@Override
public void afterTextChanged(Editable s) {
    if (inputType == INPUT_ZH) {
        int l = s.length();
        while (--l >= 0) {
            if (s.charAt(l) < 0x4E00 || s.charAt(l) > 0x9FB0) {
                s.delete(l, l + 1);
            }
        }
    }
    ((TextView) findViewById(R.id.ced_confirm)).setTextColor(TextUtils.isEmpty(s.toString().trim())
            ? context.getResources().getColor(R.color.forbid_click_color)
            : context.getResources().getColor(R.color.base_blue));
}
 
Example 16
Source File: CreditCardNumberFormattingTextWatcher.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
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 17
Source File: UrlBar.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
@Override
public boolean setComposingText(CharSequence text, int newCursorPosition) {
    Editable currentText = getText();
    int autoCompleteSpanStart = currentText.getSpanStart(mAutocompleteSpan);
    if (autoCompleteSpanStart >= 0) {
        int composingEnd = BaseInputConnection.getComposingSpanEnd(currentText);

        // On certain device/keyboard combinations, the composing regions are specified
        // with a noticeable delay after the initial character is typed, and in certain
        // circumstances it does not check that the current state of the text matches the
        // expectations of it's composing region.
        // For example, you can be typing:
        //   chrome://f
        // Chrome will autocomplete to:
        //   chrome://f[lags]
        // And after the autocomplete has been set, the keyboard will set the composing
        // region to the last character and it assumes it is 'f' as it was the last
        // character the keyboard sent.  If we commit this composition, the text will
        // look like:
        //   chrome://flag[f]
        // And if we use the autocomplete clearing logic below, it will look like:
        //   chrome://f[f]
        // To work around this, we see if the composition matches all the characters prior
        // to the autocomplete and just readjust the composing region to be that subset.
        //
        // See crbug.com/366732
        if (composingEnd == currentText.length()
                && autoCompleteSpanStart >= text.length()
                && TextUtils.equals(
                        currentText.subSequence(
                                autoCompleteSpanStart - text.length(),
                                autoCompleteSpanStart),
                        text)) {
            setComposingRegion(
                    autoCompleteSpanStart - text.length(), autoCompleteSpanStart);
        }

        // Once composing text is being modified, the autocomplete text has been accepted
        // or has to be deleted.
        mAutocompleteSpan.clearSpan();
        Selection.setSelection(currentText, autoCompleteSpanStart);
        currentText.delete(autoCompleteSpanStart, currentText.length());
    }
    return super.setComposingText(text, newCursorPosition);
}
 
Example 18
Source File: FormattedEditText.java    From FormatEditText with MIT License 4 votes vote down vote up
private void formatTextWhenAppend(final Editable editable, int start, int before, int count) {
    mIsFormatted = true;
    final boolean filter = mFilterRestoreTextChangeEvent;
    super.removeTextChangedListener(mTextWatcher);
    InputFilter[] filters = editable.getFilters();
    editable.setFilters(EMPTY_FILTERS);
    int selectionStart, selectionEnd;
    if (!filter) {
        selectionStart = Selection.getSelectionStart(editable);
        selectionEnd = Selection.getSelectionEnd(editable);
        editable.setSpan(SELECTION_SPAN, selectionStart, selectionEnd, Spanned.SPAN_MARK_MARK);
    }
    if (mMode < MODE_MASK) {
        boolean appendedLast = start > mHolders[mHolders.length - 1].index;
        if (!appendedLast) {
            formatDefined(editable, start, false);
        }
    } else {
        formatMask(editable, start, false);
    }
    if (!filter) {
        selectionStart = editable.getSpanStart(SELECTION_SPAN);
        selectionEnd = editable.getSpanEnd(SELECTION_SPAN);
        editable.removeSpan(SELECTION_SPAN);
        editable.setFilters(filters);
        if (mLengthFilterDelegate != null) {
            CharSequence out =
                    mLengthFilterDelegate.mFilter.filter(
                            editable, 0, editable.length(), EMPTY_SPANNED, 0, 0);
            if (out != null) {
                editable.delete(out.length(), editable.length());
            }
        }
        Selection.setSelection(
                editable,
                Math.min(selectionStart, editable.length()),
                Math.min(selectionEnd, editable.length()));
    } else {
        editable.setFilters(filters);
    }
    mIsFormatted = false;
    super.addTextChangedListener(mTextWatcher);
}
 
Example 19
Source File: RecipientEditTextView.java    From ChipsLibrary with Apache License 2.0 4 votes vote down vote up
@Override
public void onTextChanged(final CharSequence s,final int start,final int before,final int count)
  {
  // The user deleted some text OR some text was replaced; check to
  // see if the insertion point is on a space
  // following a chip.
  if(count!=before)
    {
    final DrawableRecipientChip[] chips=getSpannable().getSpans(0,getText().length(),DrawableRecipientChip.class);
    final int chipsCount=chips.length;
    if(mPreviousChipsCount>chipsCount&&mChipListener!=null)
      mChipListener.onDataChanged();
    mPreviousChipsCount=chipsCount;
    }
  if(before-count==1)
    {
    // If the item deleted is a space, and the thing before the
    // space is a chip, delete the entire span.
    final int selStart=getSelectionStart();
    final DrawableRecipientChip[] repl=getSpannable().getSpans(selStart,selStart,DrawableRecipientChip.class);
    if(repl.length>0)
      {
      // There is a chip there! Just remove it.
      final Editable editable=getText();
      // Add the separator token.
      final int tokenStart=mTokenizer.findTokenStart(editable,selStart);
      int tokenEnd=mTokenizer.findTokenEnd(editable,tokenStart);
      tokenEnd=tokenEnd+1;
      if(tokenEnd>editable.length())
        tokenEnd=editable.length();
      editable.delete(tokenStart,tokenEnd);
      getSpannable().removeSpan(repl[0]);
      }
    }
  else if(count>before)
    if(mSelectedChip!=null&&isGeneratedContact(mSelectedChip))
      if(lastCharacterIsCommitCharacter(s))
        {
        commitByCharacter();
        return;
        }
  }
 
Example 20
Source File: BaseKeyListener.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private boolean deleteUntilWordBoundary(View view, Editable content, boolean isForwardDelete) {
    int currentCursorOffset = Selection.getSelectionStart(content);

    // If there is a selection, do nothing.
    if (currentCursorOffset != Selection.getSelectionEnd(content)) {
        return false;
    }

    // Early exit if there is no contents to delete.
    if ((!isForwardDelete && currentCursorOffset == 0) ||
        (isForwardDelete && currentCursorOffset == content.length())) {
        return false;
    }

    WordIterator wordIterator = null;
    if (view instanceof TextView) {
        wordIterator = ((TextView)view).getWordIterator();
    }

    if (wordIterator == null) {
        // Default locale is used for WordIterator since the appropriate locale is not clear
        // here.
        // TODO: Use appropriate locale for WordIterator.
        wordIterator = new WordIterator();
    }

    int deleteFrom;
    int deleteTo;

    if (isForwardDelete) {
        deleteFrom = currentCursorOffset;
        wordIterator.setCharSequence(content, deleteFrom, content.length());
        deleteTo = wordIterator.following(currentCursorOffset);
        if (deleteTo == BreakIterator.DONE) {
            deleteTo = content.length();
        }
    } else {
        deleteTo = currentCursorOffset;
        wordIterator.setCharSequence(content, 0, deleteTo);
        deleteFrom = wordIterator.preceding(currentCursorOffset);
        if (deleteFrom == BreakIterator.DONE) {
            deleteFrom = 0;
        }
    }
    content.delete(deleteFrom, deleteTo);
    return true;
}