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

The following examples show how to use android.text.Editable#insert() . 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: ConversationFragment.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
private void highlightInConference(String nick) {
    final Editable editable = this.binding.textinput.getText();
    String oldString = editable.toString().trim();
    final int pos = this.binding.textinput.getSelectionStart();
    if (oldString.isEmpty() || pos == 0) {
        editable.insert(0, nick + ": ");
    } else {
        final char before = editable.charAt(pos - 1);
        final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
        if (before == '\n') {
            editable.insert(pos, nick + ": ");
        } else {
            if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
                if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
                    editable.insert(pos - 2, ", " + nick);
                    return;
                }
            }
            editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
            if (Character.isWhitespace(after)) {
                this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
            }
        }
    }
}
 
Example 2
Source File: ConversationFragment.java    From Pix-Art-Messenger with GNU General Public License v3.0 6 votes vote down vote up
private void highlightInConference(String nick) {
    final Editable editable = this.binding.textinput.getText();
    String oldString = editable.toString().trim();
    final int pos = this.binding.textinput.getSelectionStart();
    if (oldString.isEmpty() || pos == 0) {
        editable.insert(0, nick + ": ");
    } else {
        final char before = editable.charAt(pos - 1);
        final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
        if (before == '\n') {
            editable.insert(pos, nick + ": ");
        } else {
            if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
                if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
                    editable.insert(pos - 2, ", " + nick);
                    return;
                }
            }
            editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
            if (Character.isWhitespace(after)) {
                this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
            }
        }
    }
}
 
Example 3
Source File: MethodDescription.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onSelectThis(@NonNull IEditAreaView editorView) {
    try {
        final int length = getIncomplete().length();
        final int start = editorView.getSelectionStart() - length;

        Editable editable = editorView.getEditableText();
        editable.delete(start, editorView.getSelectionStart());
        String simpleName = JavaUtil.getSimpleName(mMethodName);
        String text = simpleName + "()" + (shouldAddSemicolon(getEditor()) ? ";" : "");
        if (getParameterTypes().size() > 0) {
            //Should end method?
            editable.insert(start, text);
            editorView.setSelection(start + simpleName.length() + 1/*(*/);
        } else {
            editable.insert(start, text);
            editorView.setSelection(start + text.length());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 4
Source File: EditMessage.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
public void insertAsQuote(String text) {
    text = text.replaceAll("(\n *){2,}", "\n").replaceAll("(^|\n)", "$1> ").replaceAll("\n$", "");
    Editable editable = getEditableText();
    int position = getSelectionEnd();
    if (position == -1) position = editable.length();
    if (position > 0 && editable.charAt(position - 1) != '\n') {
        editable.insert(position++, "\n");
    }
    editable.insert(position, text);
    position += text.length();
    editable.insert(position++, "\n");
    if (position < editable.length() && editable.charAt(position) != '\n') {
        editable.insert(position, "\n");
    }
    setSelection(position);
}
 
Example 5
Source File: NewPostActivity.java    From Ruisi with Apache License 2.0 6 votes vote down vote up
private void handleInsert(String s) {
    int start = edContent.getSelectionStart();
    int end = edContent.getSelectionEnd();
    int p = s.indexOf("[/");//相对于要插入的文本光标所在位置

    Editable edit = edContent.getEditableText();//获取EditText的文字

    if (start < 0 || start >= edit.length()) {
        edit.append(s);
    } else if (start != end && start > 0 && start < end && p > 0) {
        edit.insert(start, s.substring(0, p));//插入bbcode标签开始部分
        end = end + p;
        edit.insert(end, s.substring(p));//插入bbcode标签结束部分
        p = end - start;
    } else {
        edit.insert(start, s);//光标所在位置插入文字
    }

    if (p > 0) {
        edContent.setSelection(start + p);
    }
}
 
Example 6
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 7
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 8
Source File: EditorFragment.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
private void markdownCode() {
    final EditText et = mContentET;
    Editable editable = et.getText();
    int start = et.getSelectionStart();
    if (et.hasSelection()) {
        int end = et.getSelectionEnd();
        editable.insert(end, CODE);
        editable.insert(start, CODE);
        et.setSelection(start + 1, end + 1);
    } else {
        editable.insert(start, CODE2);
        et.setSelection(start + 1);
    }
}
 
Example 9
Source File: RichTextWatcher.java    From RichEditor with MIT License 5 votes vote down vote up
@Override
public void afterTextChanged(Editable s) {
    if (s.toString().length() < beforeEditContentLen) {
        // 说明删除了字符
        if (s.length() > 0) {
            handleDelete();
        }
        lastEditTextContent = s.toString();
        return;
    }

    int cursorPos = mEditText.getSelectionStart();
    String editContent = s.toString();
    // 如果是删除imageSpan,然后再执行undo的时候,不要在插入'\n',否则可能导致死循环
    if (needInsertBreakLinePosAfterImage != -1 &&
            cursorPos > 0 && editContent.charAt(cursorPos - 1) != '\n'
            && !isInUndo(lastEditTextContent, editContent)) {
        //在imageSpan后面输入了文字(除了'\n'),则需要换行
        s.insert(needInsertBreakLinePosAfterImage, "\n");
    }

    if (isNeedInsertBreakLineBeforeImage && cursorPos >= 0) {
        // 在ImageSpan前输入回车, 则需要将光标移动到上一个行
        // 在ImageSpan前输入文字(除了'\n'),则需要先换行,在将光标移动到上一行
        if (cursorPos > 0 && editContent.charAt(cursorPos - 1) != '\n') {
            s.insert(cursorPos, "\n");
        }
        mEditText.setSelection(cursorPos);
    }

    if (cursorPos > 0 && editContent.charAt(cursorPos - 1) == '\n' && !editContent.equals(lastEditTextContent)) {
        // 输入了回车, 需要断开上一行的样式(包括inline和block)
        lastEditTextContent = s.toString();
        changeLastBlockOrInlineSpanFlag();
    }

    lastEditTextContent = s.toString();
}
 
Example 10
Source File: CreditCardNumberFormattingTextWatcher.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
public static void insertSeparators(Editable s) {
    final int[] positions = {4, 9, 14 };
    for (int i : positions) {
        if (s.length() > i) {
            s.insert(i, SEPARATOR);
        }
    }
}
 
Example 11
Source File: SimpleCommonUtils.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public static EmoticonClickListener getCommonEmoticonClickListener(final EditText editText) {
        return new EmoticonClickListener() {
            @Override
            public void onEmoticonClick(Object o, int actionType, boolean isDelBtn) {
                if (isDelBtn) {
                    SimpleCommonUtils.delClick(editText);
                } else {
                    if (o == null) {
                        return;
                    }
                    if (actionType == Constants.EMOTICON_CLICK_TEXT) {
                        String content = null;
//                        if (o instanceof EmojiBean) {
//                            content = ((EmojiBean) o).emoji;
//                        } else
                            if (o instanceof EmoticonEntity) {
                            content = ((EmoticonEntity) o).getContent();
                        }

                        if (TextUtils.isEmpty(content)) {
                            return;
                        }
                        int index = editText.getSelectionStart();
                        Editable editable = editText.getText();
                        editable.insert(index, content);
                    }
                }
            }
        };
    }
 
Example 12
Source File: EaseChatPrimaryMenu.java    From Study_Android_Demo with Apache License 2.0 5 votes vote down vote up
@Override
public void onTextInsert(CharSequence text) {
   int start = editText.getSelectionStart();
   Editable editable = editText.getEditableText();
   editable.insert(start, text);
   setModeKeyboard();
}
 
Example 13
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 14
Source File: PaddingChooser.java    From SuntimesWidget with GNU General Public License v3.0 5 votes vote down vote up
private void insertStartBracket(Editable editable)
{
    if (editable.charAt(0) != brackets[0])
    {
        editable.insert(0, brackets[0]+"");
    }
}
 
Example 15
Source File: ChatActivity.java    From emoji with Apache License 2.0 5 votes vote down vote up
@Override
	public void onEmoticonTap(String drawableId) {
		Editable editable = mChatEditorTxt.getText();
		int index = mChatEditorTxt.getSelectionEnd();
		String emo = EmojiParser.getInstance(this).convertToUnicode(drawableId);
		SpannableStringBuilder builder = new SpannableStringBuilder(emo);
		int resId = getResources().getIdentifier("emoji_" + drawableId, "drawable", getPackageName());
		Drawable d = getResources().getDrawable(resId);
		d.setBounds(0, 0, 30, 30);
		ImageSpan span = new ImageSpan(d);
		builder.setSpan(span, 0, emo.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		if (index < mChatEditorTxt.length()) {
			editable.insert(index, builder);
		}else {
			editable.append(builder);
		}
		mChatEditorTxt.setSelection(index + emo.length());
		
		
//		drawableSrc = "emoji_" + drawableId;
//		ImageGetter imageGetter = new ImageGetter() {
//			public Drawable getDrawable(String source) {
//				int id = ChatActivity.this.getResources().getIdentifier(source, "drawable", getPackageName());
//				Drawable d = ChatActivity.this.getResources().getDrawable(id);
//				d.setBounds(0, 0, 24, 24);
//				return d;
//			}
//		};
//		CharSequence cs1 = Html.fromHtml("<img src='" + drawableSrc + "'/>", imageGetter, null);
//		int index = mChatEditorTxt.getSelectionStart();
//		Editable etb = mChatEditorTxt.getText();
//		int length = etb.length();
//		if (index < length) {
//			etb.insert(index, cs1);
//		} else {
//			mChatEditorTxt.append(cs1);
//		}
//		mChatEditorTxt.setSelection(index + 1);
	}
 
Example 16
Source File: WriteWeiboWithAppSrcActivity.java    From iBeebo with GNU General Public License v3.0 4 votes vote down vote up
protected void insertTopic() {
    int currentCursor = mEditText.getSelectionStart();
    Editable editable = mEditText.getText();
    editable.insert(currentCursor, "##");
    mEditText.setSelection(currentCursor + 1);
}
 
Example 17
Source File: CreditCardBaseTextWatcher.java    From credit_card_lib with MIT License 4 votes vote down vote up
protected void insertSpace(Editable editable, int index, char ch) {
    if (Character.isDigit(ch) && TextUtils.split(editable.toString(), String.valueOf(SPACE)).length <= 3) {
        mIsChangedInside = true;
        editable.insert(index, String.valueOf(SPACE));
    }
}
 
Example 18
Source File: PbChatActivity.java    From imsdk-android with MIT License 4 votes vote down vote up
@Override
public void onTextAdd(String content, int start, int length) {
    Editable edit = edit_msg.getEditableText();
    edit.insert(start, content);
}
 
Example 19
Source File: SolveTimeNumberTextWatcher.java    From TwistyTimer with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void afterTextChanged(Editable s) {
    if (isFormatting)
        return;

    isFormatting = true;

    // Since the keyboard input type is "number", we can't punctuation with the actual
    // filters, so we clear them and restore once we finish formatting
    InputFilter[] filters = s.getFilters(); // save filters
    s.setFilters(new InputFilter[] {});     // clear filters


    // Clear all formatting from editable
    // Regex matches the characters ':', '.', 'h' and a leading zero, if present
    mUnformatted = s.toString().replaceAll("^0+|[h]|:|\\.", "");
    mLen = mUnformatted.length();

    s.clear();
    s.insert(0, mUnformatted);


    if (mLen <= 2 && mLen > 0) { // 12 -> 0.12
        s.insert(0, "0.");
    } else if (mLen == 3) { // 123 -> 1.23
        s.insert(1, ".");
    } else if (mLen == 4) { // 1234 -> 12.34
        s.insert(2, ".");
    } else if (mLen == 5) { // 12345 -> 1:23.45
        s.insert(1, ":");
        s.insert(4, ".");
    } else if (mLen == 6) { // 123456 -> 12:34.56
        s.insert(2, ":");
        s.insert(5, ".");
    } else if (mLen == 7) { // 1234567 -> 1:23:45.67
        s.insert(1, "h");
        s.insert(4, ":");
        s.insert(7, ".");
    } else if (mLen == 8) { // 12345678 -> 12:34:56.78
        s.insert(2, "h");
        s.insert(5, ":");
        s.insert(8, ".");
    }

    isFormatting = false;

    // Restore filters
    s.setFilters(filters);
}
 
Example 20
Source File: RepostWeiboWithAppSrcActivity.java    From iBeebo with GNU General Public License v3.0 4 votes vote down vote up
protected void insertTopic() {
    int currentCursor = mEditText.getSelectionStart();
    Editable editable = mEditText.getText();
    editable.insert(currentCursor, "##");
    mEditText.setSelection(currentCursor + 1);
}