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

The following examples show how to use android.text.Editable#replace() . 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: TokenCompleteTextView.java    From TokenAutoComplete with Apache License 2.0 6 votes vote down vote up
/**
 * A String of text that is shown before all the tokens inside the EditText
 * (Think "To: " in an email address field. I would advise against this: use a label and a hint.
 *
 * @param p String with the hint
 */
public void setPrefix(CharSequence p) {
    //Have to clear and set the actual text before saving the prefix to avoid the prefix filter
    CharSequence prevPrefix = prefix;
    prefix = p;
    Editable text = getText();
    if (text != null) {
        internalEditInProgress = true;
        if (prevPrefix != null) {
            text.replace(0, prevPrefix.length(), p);
        } else {
            text.insert(0, p);
        }
        internalEditInProgress = false;
    }
    //prefix = p;

    updateHint();
}
 
Example 2
Source File: RecipientEditTextView.java    From ChipsLibrary with Apache License 2.0 6 votes vote down vote up
private void handleEdit(final int start,final int end)
{
if(start==-1||end==-1)
  {
  // This chip no longer exists in the field.
  dismissDropDown();
  return;
  }
// This is in the middle of a chip, so select out the whole chip
// and commit it.
final Editable editable=getText();
setSelection(end);
final String text=getText().toString().substring(start,end);
if(!TextUtils.isEmpty(text))
  {
  final RecipientEntry entry=RecipientEntry.constructFakeEntry(text,isValid(text));
  QwertyKeyListener.markAsReplaced(editable,start,end,"");
  final CharSequence chipText=createChip(entry,false);
  final int selEnd=getSelectionEnd();
  if(chipText!=null&&start>-1&&selEnd>-1)
    editable.replace(start,selEnd,chipText);
  }
dismissDropDown();
}
 
Example 3
Source File: FormatWatcher.java    From decoro with Apache License 2.0 6 votes vote down vote up
public void refreshMask(@Nullable final CharSequence initialValue) {
    final boolean initial = this.mask == null;

    this.mask = createMask();
    checkMask();

    final boolean initiationNeeded = initialValue != null;
    diffMeasures = new DiffMeasures();
    if (initiationNeeded) {
        diffMeasures.setCursorPosition(mask.insertFront(initialValue));
    }

    if ((!initial || initWithMask || initiationNeeded) && isInstalled()) {
        selfEdit = true;
        final String formattedInitialValue = mask.toString();
        if (textView instanceof EditText) {
            final Editable editable = (Editable) textView.getText();
            editable.replace(0, editable.length(), formattedInitialValue, 0, formattedInitialValue.length());
        } else {
            textView.setText(formattedInitialValue);
        }
        setSelection(mask.getInitialInputPosition());
        selfEdit = false;
    }
}
 
Example 4
Source File: Main.java    From JotaTextEditor with Apache License 2.0 6 votes vote down vote up
public void onSearchFinished(ArrayList<Record> data) {
    mSearchResult = null;

    Editable text = mEditor.getEditableText();
    CharSequence replaceword = mReplaceWord;
    mChangeCancel = true;

    if (data.size() > 100) {
        mEditor.enableUndo(false);
    }
    for (int i = data.size() - 1; i >= 0; i--) {
        Record record = data.get(i);
        text.replace(record.start, record.end, replaceword);
    }
    mChangeCancel = false;
    onChanged();
    mEditor.enableUndo(true);
}
 
Example 5
Source File: UndoRedoSupportEditText.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
public void undo() {
    EditItem edit = mEditHistory.getPrevious();
    if (edit == null) {
        return;
    }

    Editable editable = mTextView.getEditableText();
    int start = edit.start;
    int end = start + (edit.after != null ? edit.after.length() : 0);

    mIsUndoOrRedo = true;
    editable.replace(start, end, edit.before);
    mIsUndoOrRedo = false;

    for (Object o : editable.getSpans(0, editable.length(), UnderlineSpan.class)) {
        editable.removeSpan(o);
    }

    Selection.setSelection(editable, edit.before == null ? start : (start + edit.before.length()));
}
 
Example 6
Source File: UndoRedoHelper.java    From mua with MIT License 6 votes vote down vote up
/**
 * Perform redo.
 */
public void redo() {
    EditItem edit = mEditHistory.getNext();
    if (edit == null) {
        return;
    }

    Editable text = mTextView.getEditableText();
    int start = edit.mmStart;
    int end = start + (edit.mmBefore != null ? edit.mmBefore.length() : 0);

    mIsUndoOrRedo = true;
    text.replace(start, end, edit.mmAfter);
    mIsUndoOrRedo = false;

    // This will get rid of underlines inserted when editor tries to come
    // up with a suggestion.
    for (Object o : text.getSpans(0, text.length(), UnderlineSpan.class)) {
        text.removeSpan(o);
    }

    Selection.setSelection(text, edit.mmAfter == null ? start
            : (start + edit.mmAfter.length()));
}
 
Example 7
Source File: EditorFragment.java    From android-discourse with Apache License 2.0 6 votes vote down vote up
private void insertMarkdownPicture(String des, String url) {
    final EditText et = mContentET;
    Editable editable = et.getText();
    int start = et.getSelectionStart();
    int desL = des.length();
    int sbL = 1;
    // 当弹出对话框的时候, 文本的选择状态会消失。
    if (mUploadSelection.isEmpty()) {
        editable.insert(start, String.format(MARKDOWN_IMG, des, url));
    } else {
        start = mUploadSelection.start;
        int end = mUploadSelection.end;
        editable.replace(start, end, String.format(MARKDOWN_IMG, des, url));
        // editable.insert(start, SB);
        // editable.insert(start + desL + sbL, SB2);
        // editable.insert(start + desL + sbL + sbL, "(" + url + ")");
        et.setSelection(start + sbL, start + sbL + desL);
    }
}
 
Example 8
Source File: Editor.java    From turbo-editor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Perform undo.
 */
public void undo() {
    EditItem edit = mEditHistory.getPrevious();
    if (edit == null) {
        return;
    }

    Editable text = getEditableText();
    int start = edit.mmStart;
    int end = start + (edit.mmAfter != null
            ? edit.mmAfter.length() : 0);

    mIsUndoOrRedo = true;
    text.replace(start, end, edit.mmBefore);
    mIsUndoOrRedo = false;

    // This will get rid of underlines inserted when editor tries to come
    // up with a suggestion.
    for (Object o : text.getSpans(0,
            text.length(), UnderlineSpan.class)) {
        text.removeSpan(o);
    }

    Selection.setSelection(text,
            edit.mmBefore == null ? start
                    : (start + edit.mmBefore.length()));
}
 
Example 9
Source File: MarkdownEditor.java    From Elephant with Apache License 2.0 5 votes vote down vote up
private void insertHorizontalLine(Editable e) {
    int selectionStart = mEditText.getSelectionStart();
    int selectionEnd = mEditText.getSelectionEnd();
    final String titleTemplate = "---\n";
    e.replace(selectionStart, selectionEnd, titleTemplate);
    // start from "t", end to "e"
    mEditText.setSelection(selectionStart + 4, selectionStart + 4);
}
 
Example 10
Source File: MarkdownEditor.java    From Elephant with Apache License 2.0 5 votes vote down vote up
private void insertList(Editable e) {
    int selectionStart = mEditText.getSelectionStart();
    int selectionEnd = mEditText.getSelectionEnd();
    final String listTemplate = "- List Item";
    e.replace(selectionStart, selectionEnd, listTemplate);
    // start from "L", end to "m"
    mEditText.setSelection(selectionStart + 2, selectionStart + 11);
}
 
Example 11
Source File: TextFrag.java    From PowerFileExplorer with GNU General Public License v3.0 5 votes vote down vote up
public void run() {
    if (mSharedString != null && mSharedString.length() > 0) {
        mProcNew.run();
        Editable text = mEditor.getText();
        text.replace(0, 0, mSharedString);
        mSharedString = null;
    }
}
 
Example 12
Source File: PatternedTextWatcher.java    From PatternedTextWatcher with MIT License 5 votes vote down vote up
/**
 * Check if current string was changed, so that editable should be also changed.
 *
 * @param s  the editable to change.
 * @param sb current string.
 */
private void checkIfReplaceIsNeeded(Editable s, StringBuilder sb) {
  lastText = sb.toString();
  if (!s.toString().equals(lastText)) {
    s.replace(0, s.length(), sb);
  }
}
 
Example 13
Source File: Main.java    From JotaTextEditor with Apache License 2.0 5 votes vote down vote up
public void run() {
    if (mSharedString != null && mSharedString.length() > 0) {
        mProcNew.run();
        Editable text = mEditor.getText();
        text.replace(0, 0, mSharedString);
        mSharedString = null;
    }
}
 
Example 14
Source File: InputPanel.java    From NIM_Android_UIKit with MIT License 5 votes vote down vote up
/**
 * *************** IEmojiSelectedListener ***************
 */
@Override
public void onEmojiSelected(String key) {
    Editable mEditable = messageEditText.getText();
    if (key.equals("/DEL")) {
        messageEditText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
    } else {
        int start = messageEditText.getSelectionStart();
        int end = messageEditText.getSelectionEnd();
        start = (start < 0 ? 0 : start);
        end = (start < 0 ? 0 : end);
        mEditable.replace(start, end, key);
    }
}
 
Example 15
Source File: MainActivity.java    From Autocomplete with Apache License 2.0 5 votes vote down vote up
private void setupMentionsAutocomplete() {
    EditText edit = findViewById(R.id.multi);
    float elevation = 6f;
    Drawable backgroundDrawable = new ColorDrawable(Color.WHITE);
    AutocompletePolicy policy = new CharPolicy('@'); // Look for @mentions
    AutocompletePresenter<User> presenter = new UserPresenter(this);
    AutocompleteCallback<User> callback = new AutocompleteCallback<User>() {
        @Override
        public boolean onPopupItemClicked(@NonNull Editable editable, @NonNull User item) {
            // Replace query text with the full name.
            int[] range = CharPolicy.getQueryRange(editable);
            if (range == null) return false;
            int start = range[0];
            int end = range[1];
            String replacement = item.getUsername();
            editable.replace(start, end, replacement);
            // This is better done with regexes and a TextWatcher, due to what happens when
            // the user clears some parts of the text. Up to you.
            editable.setSpan(new StyleSpan(Typeface.BOLD), start, start+replacement.length(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            return true;
        }
        public void onPopupVisibilityChanged(boolean shown) {}
    };

    mentionsAutocomplete = Autocomplete.<User>on(edit)
            .with(elevation)
            .with(backgroundDrawable)
            .with(policy)
            .with(presenter)
            .with(callback)
            .build();
}
 
Example 16
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 17
Source File: ContactEditText.java    From material with Apache License 2.0 5 votes vote down vote up
private void replaceSpan(RecipientSpan span, Recipient newRecipient){
    Editable text = getText();
    int start = text.getSpanStart(span);
    int end = text.getSpanEnd(span);
    String replace = newRecipient.number;
    text.replace(start, end - 2, newRecipient.number, 0, replace.length());
    span.setRecipient(newRecipient);
    text.setSpan(span, start, start + replace.length() + 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
 
Example 18
Source File: RecipientEditTextView.java    From ChipsLibrary with Apache License 2.0 4 votes vote down vote up
private void processReplacements(final List<DrawableRecipientChip> recipients,final List<DrawableRecipientChip> replacements)
{
if(replacements!=null&&replacements.size()>0)
  {
  final Runnable runnable=new Runnable()
    {
      @Override
      public void run()
        {
        final Editable text=new SpannableStringBuilder(getText());
        int i=0;
        for(final DrawableRecipientChip chip : recipients)
          {
          final DrawableRecipientChip replacement=replacements.get(i);
          if(replacement!=null)
            {
            final RecipientEntry oldEntry=chip.getEntry();
            final RecipientEntry newEntry=replacement.getEntry();
            final boolean isBetter=RecipientAlternatesAdapter.getBetterRecipient(oldEntry,newEntry)==newEntry;
            if(isBetter)
              {
              // Find the location of the chip in the text currently shown.
              final int start=text.getSpanStart(chip);
              if(start!=-1)
                {
                // Replacing the entirety of what the chip represented,
                // including the extra space dividing it from other chips.
                final int end=Math.min(text.getSpanEnd(chip)+1,text.length());
                text.removeSpan(chip);
                // Make sure we always have just 1 space at the end to
                // separate this chip from the next chip.
                final SpannableString displayText=new SpannableString(createAddressText(replacement.getEntry()).trim()+" ");
                displayText.setSpan(replacement,0,displayText.length()-1,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                // Replace the old text we found with with the new display
                // text, which now may also contain the display name of the
                // recipient.
                text.replace(start,end,displayText);
                replacement.setOriginalText(displayText.toString());
                replacements.set(i,null);
                recipients.set(i,replacement);
                }
              }
            }
          i++;
          }
        setText(text);
        }
    };
  if(Looper.myLooper()==Looper.getMainLooper())
    runnable.run();
  else mHandler.post(runnable);
  }
}
 
Example 19
Source File: TextChipsEditView.java    From talk-android with MIT License 4 votes vote down vote up
/**
 * Create the more chip. The more chip is text that replaces any chips that
 * do not fit in the pre-defined available space when the
 * RecipientEditTextView loses focus.
 */
// Visible for testing.
/* package */ void createMoreChip() {
    if (mNoChips) {
        createMoreChipPlainText();
        return;
    }

    if (!mShouldShrink) {
        return;
    }
    ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class);
    if (tempMore.length > 0) {
        getSpannable().removeSpan(tempMore[0]);
    }
    DrawableRecipientChip[] recipients = getSortedRecipients();

    if (recipients == null || recipients.length <= CHIP_LIMIT) {
        mMoreChip = null;
        return;
    }
    Spannable spannable = getSpannable();
    int numRecipients = recipients.length;
    int overage = numRecipients - CHIP_LIMIT;
    MoreImageSpan moreSpan = createMoreSpan(overage);
    mRemovedSpans = new ArrayList<DrawableRecipientChip>();
    int totalReplaceStart = 0;
    int totalReplaceEnd = 0;
    Editable text = getText();
    for (int i = numRecipients - overage; i < recipients.length; i++) {
        mRemovedSpans.add(recipients[i]);
        if (i == numRecipients - overage) {
            totalReplaceStart = spannable.getSpanStart(recipients[i]);
        }
        if (i == recipients.length - 1) {
            totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
        }
        if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
            int spanStart = spannable.getSpanStart(recipients[i]);
            int spanEnd = spannable.getSpanEnd(recipients[i]);
            recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
        }
        spannable.removeSpan(recipients[i]);
    }
    if (totalReplaceEnd < text.length()) {
        totalReplaceEnd = text.length();
    }
    int end = Math.max(totalReplaceStart, totalReplaceEnd);
    int start = Math.min(totalReplaceStart, totalReplaceEnd);
    SpannableString chipText = new SpannableString(text.subSequence(start, end));
    chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    text.replace(start, end, chipText);
    mMoreChip = moreSpan;
    // If adding the +more chip goes over the limit, resize accordingly.
    if (!isPhoneQuery() && getLineCount() > mMaxLines) {
        setMaxLines(getLineCount());
    }
}
 
Example 20
Source File: JotaTextKeyListener.java    From JotaTextEditor with Apache License 2.0 4 votes vote down vote up
@Override
public boolean onKeyDown(View view, Editable content, int keyCode, KeyEvent event) {
    boolean result = super.onKeyDown(view, content, keyCode, event);

    // auto indent
    if ( sAutoIndent && keyCode == KeyEvent.KEYCODE_ENTER ){

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

            // search head of previous line
            int prev = a-2;
            while( prev >=0 && content.charAt(prev)!='\n' ){
                prev--;
            }
            prev ++;
            int pos = prev;
            while(  content.charAt(pos)==' ' || content.charAt(pos)=='\t' || content.charAt(pos)=='\u3000'){
                pos++;
            }
            int len = pos-prev;
            if ( len > 0  ){
                char [] dest = new char[len];
                content.getChars(prev, pos, dest, 0);

                content.replace(a,b, new String(dest) );
                Selection.setSelection(content, a+len);
            }
        }
    }
    if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB ){
        if (keyCode == KEYCODE_FORWARD_DEL ) {
            if ( (event.getMetaState() & 512) == 0 ){       // workaround for Galaxy Note
                forwardDelete(view, content, keyCode, event);
                return true;
            }
        }
    }
    return result;
}