Java Code Examples for android.text.Editable

The following examples show how to use android.text.Editable. 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
Source Project: zulip-android   Source File: ListTagHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Closes a list item.
 *
 * @param text
 * @param indentation
 */
public final void closeItem(final Editable text, final int indentation) {
    if (text.length() > 0 && text.charAt(text.length() - 1) != '\n') {
        text.append("\n");
    }
    final Object[] replaces = getReplaces(text, indentation);
    final int len = text.length();
    final ListTag listTag = getLast(text);
    final int where = text.getSpanStart(listTag);
    text.removeSpan(listTag);
    if (where != len) {
        for (Object replace : replaces) {
            text.setSpan(replace, where, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
}
 
Example 2
Source Project: Dashchan   Source File: SafePasteEditText.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean onTextContextMenuItem(int id) {
	if (id == android.R.id.paste) {
		Editable editable = getEditableText();
		InputFilter[] filters = editable.getFilters();
		InputFilter[] tempFilters = new InputFilter[filters != null ? filters.length + 1 : 1];
		if (filters != null) {
			System.arraycopy(filters, 0, tempFilters, 1, filters.length);
		}
		tempFilters[0] = SPAN_FILTER;
		editable.setFilters(tempFilters);
		try {
			return super.onTextContextMenuItem(id);
		} finally {
			editable.setFilters(filters);
		}
	} else {
		return super.onTextContextMenuItem(id);
	}
}
 
Example 3
Source Project: RichEditText   Source File: RichEditText.java    License: 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 4
Source Project: iZhihu   Source File: Main.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void afterTextChanged(Editable editable) {
    searchString = editable.toString().trim();

    if (searchString != null && searchString.length() > 0) {
        new SearchQuestionTask(context, new SearchQuestionTask.Callback() {
            @Override
            public void onPreExecute() {
                // ...
            }

            @Override
            public void onPostExecute(ArrayList<Question> result) {
                searchedQuestions.clear();
                searchedQuestions.addAll(result);
                if (questionsAdapter != null) {
                    questionsAdapter.notifyDataSetChanged();
                }
            }
        }).execute(searchString);
    }
}
 
Example 5
Source Project: BluetoothHidEmu   Source File: KeyboardKeyListener.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean onKeyDown(View view, Editable content, int keyCode, KeyEvent event) {
    switch (keyCode) {
    
    case KeyEvent.KEYCODE_ENTER:
        TextKeyListener.clear(content);
        mHidPayload.assemblePayload(HidKeyPair.ENTER);
        mSocketManager.sendPayload(mHidPayload);
        return true;
    case KeyEvent.KEYCODE_DEL:
    	mHidPayload.assemblePayload(HidKeyPair.DEL);
        mSocketManager.sendPayload(mHidPayload);
    case KeyEvent.KEYCODE_VOLUME_UP:
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        mHidPayload.assemblePayload(keyCode);
        mSocketManager.sendPayload(mHidPayload);
    default:
        return mTextKeyListener.onKeyDown(view, content, keyCode, event);
    }
}
 
Example 6
@Override
public void sendText(@NotNull String txt) {
    if (isEmpty(txt)) return;
    View view = getWindow().getDecorView().findFocus();
    if (view instanceof EditText) {
        EditText editText = (EditText) view;
        int start = editText.getSelectionStart();
        int end = editText.getSelectionEnd();
        Editable edit = editText.getEditableText();//获取EditText的文字
        if (start < 0 || start >= edit.length()) {
            edit.append(txt);
        } else {
            edit.replace(start, end, txt);//光标所在位置插入文字
        }
    }
}
 
Example 7
Source Project: DevUtils   Source File: EditTextUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 追加内容
 * @param editText {@link EditText}
 * @param content  文本内容
 * @param start    开始添加的位置
 * @param isSelect 是否设置光标
 * @param <T>      泛型
 * @return {@link EditText}
 */
public static <T extends EditText> T insert(final T editText, final CharSequence content, final int start, final boolean isSelect) {
    if (editText != null && !TextUtils.isEmpty(content)) {
        try {
            Editable editable = editText.getText();
            // 在指定位置 追加内容
            editable.insert(start, content);
            // 设置光标
            if (isSelect) {
                editText.setSelection(editText.getText().toString().length());
            }
        } catch (Exception e) {
            LogPrintUtils.eTag(TAG, e, "insert");
        }
    }
    return editText;
}
 
Example 8
Source Project: android_9.0.0_r45   Source File: BaseInputConnection.java    License: 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 9
Source Project: android-pin   Source File: BaseViewController.java    License: MIT License 6 votes vote down vote up
private void initKeyboard() {
    mKeyboardView.setOnKeyboardActionListener(new PinKeyboardView.PinPadActionListener() {
        @Override
        public void onKey(int primaryCode, int[] keyCodes) {
            Editable e = mPinputView.getText();
            if (primaryCode == PinKeyboardView.KEYCODE_DELETE) {
                int len = e.length();
                if (len == 0) {
                    return;
                }
                e.delete(len - 1, e.length());
            } else {
                mPinputView.getText().append((char) primaryCode);
            }
        }
    });
    mKeyboardView.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == ACTION_DOWN && getConfig().shouldVibrateOnKey()) {
                VibrationHelper.vibrate(mContext, getConfig().vibrateDuration());
            }
            return false;
        }
    });
}
 
Example 10
Source Project: ForPDA   Source File: Html.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static void startBlockElement(Editable text, Attributes attributes, int margin) {
    final int len = text.length();
    if (margin > 0) {
        appendNewlines(text, margin);
        start(text, new Newline(margin));
    }
    String style = attributes.getValue("", "style");
    if (style != null) {
        Matcher m = getTextAlignPattern().matcher(style);
        if (m.find()) {
            String alignment = m.group(1);
            if (alignment.equalsIgnoreCase("start")) {
                start(text, new Alignment(Layout.Alignment.ALIGN_NORMAL));
            } else if (alignment.equalsIgnoreCase("center")) {
                start(text, new Alignment(Layout.Alignment.ALIGN_CENTER));
            } else if (alignment.equalsIgnoreCase("end")) {
                start(text, new Alignment(Layout.Alignment.ALIGN_OPPOSITE));
            }
        }
    }
}
 
Example 11
Source Project: talk-android   Source File: TextChipsEditView.java    License: MIT License 6 votes vote down vote up
/**
 * Handles pasting a {@link ClipData} to this {@link TextChipsEditView}.
 */
private void handlePasteClip(ClipData clip) {
    removeTextChangedListener(mTextWatcher);

    if (clip != null && clip.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
        for (int i = 0; i < clip.getItemCount(); i++) {
            CharSequence paste = clip.getItemAt(i).getText();
            if (paste != null) {
                int start = getSelectionStart();
                int end = getSelectionEnd();
                Editable editable = getText();
                if (start >= 0 && end >= 0 && start != end) {
                    editable.append(paste, start, end);
                } else {
                    editable.insert(end, paste);
                }
                handlePasteAndReplace();
            }
        }
    }

    mHandler.post(mAddTextWatcher);
}
 
Example 12
Source Project: html-textview   Source File: HtmlTagHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get last marked position of a specific tag kind (private class)
 */
private static Object getLast(Editable text, Class kind) {
    Object[] objs = text.getSpans(0, text.length(), kind);
    if (objs.length == 0) {
        return null;
    } else {
        for (int i = objs.length; i > 0; i--) {
            if (text.getSpanFlags(objs[i - 1]) == Spannable.SPAN_MARK_MARK) {
                return objs[i - 1];
            }
        }
        return null;
    }
}
 
Example 13
Source Project: ForPDA   Source File: Html.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static void endBlockElement(Editable text) {
    Newline n = getLast(text, Newline.class);
    if (n != null) {
        appendNewlines(text, n.mNumNewlines);
        text.removeSpan(n);
    }
    Alignment a = getLast(text, Alignment.class);
    if (a != null) {
        setSpanFromMark(text, a, new AlignmentSpan.Standard(a.mAlignment));
    }
}
 
Example 14
@Override
public void afterTextChanged(Editable s) {
    if (old != null) {
        if (old.isInvalid())
            old = null;
        else if (!shouldReplace(old.from, old.size, old.toChange)) {
            selfChangingText = true;
            s.replace(old.from, old.from + old.toChange.length(), old.oldText, old.from, old.from + old.size);
            old = null;
        } else {
            old = null;
            didChange();
        }
    }
}
 
Example 15
Source Project: trekarta   Source File: LocationInformation.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void afterTextChanged(Editable s) {
    if (s.length() == 0) {
        mTextInputDialog.setDescription("");
        return;
    }
    try {
        JosmCoordinatesParser.Result result = JosmCoordinatesParser.parseWithResult(s.toString());
        s.setSpan(
                new ForegroundColorSpan(mColorDarkBlue),
                0,
                result.offset,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        s.setSpan(
                new ForegroundColorSpan(mColorTextPrimary),
                result.offset,
                s.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTextInputDialog.setDescription(StringFormatter.coordinates(" ", result.coordinates.getLatitude(), result.coordinates.getLongitude()));
    } catch (IllegalArgumentException e) {
        s.setSpan(
                new ForegroundColorSpan(mColorRed),
                0,
                s.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTextInputDialog.setDescription("");
    }
}
 
Example 16
Source Project: JsDroidEditor   Source File: PreformEdit.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Override
public final void afterTextChanged(Editable s) {
    if (flag) return;
    if (s != editable) {
        editable = s;
        onEditableChanged(s);
    }
    PreformEdit.this.onTextChanged(s);
}
 
Example 17
Source Project: call_manage   Source File: ImportSpreadsheetDialog.java    License: MIT License 5 votes vote down vote up
/**
 * Validates column index lol
 *
 * @param editable
 * @param view
 */
private void validateColumnIndex(Editable editable, TextInputEditText view) {
    if (!Validator.validateColumnIndex(editable.toString())) {
        view.setError(getString(R.string.error_column_index));
    } else {
        view.setError(null);
    }
}
 
Example 18
Source Project: BlackList   Source File: MessageLengthCounter.java    License: Apache License 2.0 5 votes vote down vote up
private void update(Editable messageText) {
    int messageLength = messageText.length();

    // is there unicode character in the message?
    boolean unicode = false;
    for (int i = 0; i < messageLength; i++) {
        char c = messageText.charAt(i);
        if (Character.UnicodeBlock.of(c) != Character.UnicodeBlock.BASIC_LATIN) {
            unicode = true;
            break;
        }
    }

    // get max length of sms part depending on encoding and full length
    int length1 = (unicode ? SMS_LENGTH_UNICODE : SMS_LENGTH);
    int length2 = (unicode ? SMS_LENGTH2_UNICODE : SMS_LENGTH2);
    int partMaxLength = (messageLength > length1 ? length2 : length1);
    // create current length status info
    int partsNumber = messageLength / partMaxLength + 1;
    int partLength = partMaxLength - messageLength % partMaxLength;
    // correct length info for second part
    if (partsNumber == 2 && partLength == partMaxLength) {
        partLength = length1 - (length1 - length2) * 2;
    }

    // show current length status info
    String counterText = "" + partLength + "/" + partsNumber;
    counterTextView.setText(counterText);
}
 
Example 19
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 20
Source Project: buddycloud-android   Source File: CreateAccountActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void afterTextChanged(Editable s) {
	if (s.length() == 0) {
		showErrorToolTip(mEmailErrorTooltip,
				getString(R.string.message_account_email_invalid));
	} else {
		mEmailErrorTooltip.setVisibility(View.GONE);
	}
}
 
Example 21
Source Project: TokenAutoComplete   Source File: TokenCompleteTextView.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the list of Tokens
 *
 * @return List of tokens
 */
public List<T> getObjects() {
    ArrayList<T>objects = new ArrayList<>();
    Editable text = getText();
    if (hiddenContent != null) {
        text = hiddenContent;
    }
    for (TokenImageSpan span: text.getSpans(0, text.length(), TokenImageSpan.class)) {
        objects.add(span.getToken());
    }
    return objects;
}
 
Example 22
Source Project: MaskedEditText   Source File: MainActivity.java    License: MIT License 5 votes vote down vote up
private char[] getDigitArray(final Editable s, final int size) {
    char[] digits = new char[size];
    int index = 0;
    for (int i = 0; i < s.length() && index < size; i++) {
        char current = s.charAt(i);
        if (Character.isDigit(current)) {
            digits[index] = current;
            index++;
        }
    }
    return digits;
}
 
Example 23
Source Project: turbo-editor   Source File: Editor.java    License: 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 24
Source Project: o2oa   Source File: ChatActivity.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
        public void onEmoticonClick(Object o, int actionType, boolean isDelBtn) {

            if (isDelBtn) {
                SimpleCommonUtils.delClick(ekBar.getEtChat());
            } else {
                if (o == null) {
                    return;
                }
                if (actionType == Constants.EMOTICON_CLICK_BIGIMAGE) {
                    if (o instanceof EmoticonEntity) {
                        OnSendImage(((EmoticonEntity) o).getIconUri());
                    }
                } else {
                    String content = null;
//                    Emoji
//                    EmojiDisplay.
//                    if (o instanceof EmojiBean) {
//                        content = ((EmojiBean) o).emoji;
//                    } else
                        if (o instanceof EmoticonEntity) {
                        content = ((EmoticonEntity) o).getContent();
                    }

                    if (TextUtils.isEmpty(content)) {
                        return;
                    }
                    int index = ekBar.getEtChat().getSelectionStart();
                    Editable editable = ekBar.getEtChat().getText();
                    editable.insert(index, content);
                }
            }
        }
 
Example 25
@Override
public void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub
    String charSequence = mEditText.getText().toString();
    int count = Utility.length(charSequence);
    String text = count <= 0 ? getString(R.string.send_weibo) : count + "";
    weiTextCountTV.setText(text);
    if (count > 140) {
        weiTextCountTV.setTextColor(Color.RED);
    } else {
        weiTextCountTV.setTextColor(Color.BLACK);
    }
}
 
Example 26
Source Project: android_9.0.0_r45   Source File: EditText.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Editable getText() {
    CharSequence text = super.getText();
    // This can only happen during construction.
    if (text == null) {
        return null;
    }
    if (text instanceof Editable) {
        return (Editable) super.getText();
    }
    super.setText(text, BufferType.EDITABLE);
    return (Editable) super.getText();
}
 
Example 27
@Override
public void afterTextChanged(Editable s) {
    try {
        String string = s.toString();
        if (!TextUtils.isEmpty(string)) {
            saveNumber(getActivity(), Integer.parseInt(string));
        }
    } catch (NumberFormatException e) {
        Toast.makeText(getActivity(), "Not an integer!", Toast.LENGTH_SHORT).show();
    }
}
 
Example 28
/**
 * Helper function to remove all spans of a certain type from an {@link Editable}.
 */
private <T> void removeSpans(Editable text, Class<T> clazz) {
    T[] spans = text.getSpans(0, text.length(), clazz);
    for (T span : spans) {
        text.removeSpan(span);
    }
}
 
Example 29
Source Project: SoloPi   Source File: CaseStepNodeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void afterTextChanged(Editable s) {
    boolean result = updateNodeProperty(key, s.toString(), node);
    if (!result) {
        infoText.setText(R.string.node__invalid_param);
    } else {
        infoText.setText("");
    }
}
 
Example 30
Source Project: Aegis   Source File: EditEntryActivity.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void afterTextChanged(Editable s) {
    if (!_hasCustomIcon) {
        TextDrawable drawable = TextDrawableHelper.generate(_textIssuer.getText().toString(), _textName.getText().toString(), _iconView);
        _iconView.setImageDrawable(drawable);
    }
}