Java Code Examples for android.text.Selection#setSelection()

The following examples show how to use android.text.Selection#setSelection() . 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: PhoneFormatter.java    From CallMeMaybe with Apache License 2.0 6 votes vote down vote up
private void formatPhoneNumberInput(final Editable input) {
  final int selection = Selection.getSelectionStart(buffer);
  boolean selectionPositionRemembered = false;

  asYouTypeFormatter.clear();
  String phoneNumberText = "";

  int offset = 0;
  final int length = input.length();
  while (offset < length) {
    final int codePoint = Character.codePointAt(input, offset);
    if (Character.isDigit(codePoint)) {
      final char digit = CodePoint.toDigitChar(codePoint);
      selectionPositionRemembered = selectionPositionRemembered || offset >= selection;
      phoneNumberText = asYouTypeFormatter.inputDigit(digit, !selectionPositionRemembered);
    }
    offset += Character.charCount(codePoint);
  }

  input.replace(0, input.length(), phoneNumberText);
  if (selection != -1) {
    Selection.setSelection(input,
        selectionPositionRemembered ? asYouTypeFormatter.getRememberedPosition() : phoneNumberText.length());
  }
}
 
Example 2
Source File: UndoRedo.java    From ShaderEditor with MIT License 6 votes vote down vote up
public void undo() {
	EditItem edit = editHistory.getPrevious();
	if (edit == null) {
		return;
	}

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

	isUndoOrRedo = true;
	text.replace(start, end, edit.before);
	isUndoOrRedo = false;

	removeUnderlineSpans(text);

	Selection.setSelection(text, edit.before == null ? start
			: (start + edit.before.length()));
}
 
Example 3
Source File: Folder.java    From TurboLauncher with Apache License 2.0 6 votes vote down vote up
public void doneEditingFolderName(boolean commit) {
    mFolderName.setHint(sHintText);
    // Convert to a string here to ensure that no other state associated with the text field
    // gets saved.
    String newTitle = mFolderName.getText().toString();
    if (!SettingsProvider.getBoolean(mLauncher,
            SettingsProvider.SETTINGS_UI_HOMESCREEN_HIDE_ICON_LABELS,
            R.bool.preferences_interface_homescreen_hide_icon_labels_default)) {
        mInfo.setTitle(newTitle);
    }
    LauncherModel.updateItemInDatabase(mLauncher, mInfo);

    if (commit) {
        sendCustomAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
                String.format(getContext().getString(R.string.folder_renamed), newTitle));
    }
    // In order to clear the focus from the text field, we set the focus on ourself. This
    // ensures that every time the field is clicked, focus is gained, giving reliable behavior.
    requestFocus();

    Selection.setSelection((Spannable) mFolderName.getText(), 0, 0);
    mIsEditingName = false;
}
 
Example 4
Source File: MultiTapKeyListener.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public void run() {
    Spannable buf = mBuffer;

    if (buf != null) {
        int st = Selection.getSelectionStart(buf);
        int en = Selection.getSelectionEnd(buf);

        int start = buf.getSpanStart(TextKeyListener.ACTIVE);
        int end = buf.getSpanEnd(TextKeyListener.ACTIVE);

        if (st == start && en == end) {
            Selection.setSelection(buf, Selection.getSelectionEnd(buf));
        }

        buf.removeSpan(Timeout.this);
    }
}
 
Example 5
Source File: PersonResumeChangeFragment.java    From tysq-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    String content = etResume.getText().toString().trim();
    if (content.length() > 50) {
        String newStr = content.substring(0, 50);
        etResume.setText(newStr);
        Selection.setSelection(etResume.getText(), 50);
        content = newStr;
        ToastUtils.show(getString(R.string.resume_change_num_max));
    }
    tvNum.setText("" + content.length());
}
 
Example 6
Source File: MentionsEditText.java    From Spyglass with Apache License 2.0 5 votes vote down vote up
@Override
@NonNull
public Editable newEditable(@NonNull CharSequence source) {
    MentionsEditable text = new MentionsEditable(source);
    Selection.setSelection(text, 0);
    return text;
}
 
Example 7
Source File: ContactEditText.java    From material with Apache License 2.0 5 votes vote down vote up
@Override
public void onClick(View v) {
    int position = (Integer)v.getTag();
    if(position == 0)
        removeSpan(mSelectedSpan);
    else
        replaceSpan(mSelectedSpan, (Recipient)mReplacementAdapter.getItem(position));

    Selection.setSelection(getText(), getText().length());

    dismissReplacementPopup();
}
 
Example 8
Source File: FormattedEditText.java    From FormatEditText with MIT License 5 votes vote down vote up
@Override
public void onRestoreInstanceState(Parcelable state) {
    if (!(state instanceof SavedState)) {
        super.onRestoreInstanceState(state);
        return;
    }
    SavedState savedState = (SavedState) state;
    mMode = savedState.mMode;
    mPlaceholder = savedState.mPlaceholder;
    mEmptyPlaceholder = savedState.mEmptyPlaceholder;
    mMark = savedState.mMark;
    mPlaceholders = savedState.mPlaceholders;
    mHintText = savedState.mHintText;
    mFormatStyle = savedState.mFormatStyle;
    mShowHintWhileEmpty = savedState.mShowHintWhileEmpty;
    mHintColor = savedState.mHintColor;
    if (mMode == MODE_SIMPLE) {
        parseSimplePlaceholders();
    } else if (mMode == MODE_COMPLEX) {
        parseComplexPlaceholders();
    }
    if (savedState.mRealText != null) {
        mRestoring = true;
        super.onRestoreInstanceState(savedState.getSuperState());
        mRestoring = false;
        mFilterRestoreTextChangeEvent = true;
        setText(savedState.mRealText);
        mFilterRestoreTextChangeEvent = false;
        Editable text = getText();
        Selection.setSelection(
                text,
                Math.min(savedState.mSelectionStart, text.length()),
                Math.min(savedState.mSelectionEnd, text.length()));
    } else {
        super.onRestoreInstanceState(savedState.getSuperState());
    }
}
 
Example 9
Source File: ListSelectionManager.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
private static void startSelection(TextView textView, int start, int end) {
    final CharSequence text = textView.getText();
    if (SUPPORTED && start >= 0 && end > start && textView.isTextSelectable() && text instanceof Spannable) {
        final Spannable spannable = (Spannable) text;
        start = Math.min(start, spannable.length());
        end = Math.min(end, spannable.length());
        Selection.setSelection(spannable, start, end);
        try {
            final Object editor = FIELD_EDITOR != null ? FIELD_EDITOR.get(textView) : textView;
            METHOD_START_SELECTION.invoke(editor);
        } catch (Exception e) {
        }
    }
}
 
Example 10
Source File: LinkMovementMethod.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer,
                            MotionEvent event) {
    int action = event.getAction();

    if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
        int x = (int) event.getX();
        int y = (int) event.getY();

        x -= widget.getTotalPaddingLeft();
        y -= widget.getTotalPaddingTop();

        x += widget.getScrollX();
        y += widget.getScrollY();

        Layout layout = widget.getLayout();
        int line = layout.getLineForVertical(y);
        int off = layout.getOffsetForHorizontal(line, x);

        ClickableSpan[] links = buffer.getSpans(off, off, ClickableSpan.class);

        if (links.length != 0) {
            ClickableSpan link = links[0];
            if (action == MotionEvent.ACTION_UP) {
                if (link instanceof TextLinkSpan) {
                    ((TextLinkSpan) link).onClick(
                            widget, TextLinkSpan.INVOCATION_METHOD_TOUCH);
                } else {
                    link.onClick(widget);
                }
            } else if (action == MotionEvent.ACTION_DOWN) {
                if (widget.getContext().getApplicationInfo().targetSdkVersion
                        >= Build.VERSION_CODES.P) {
                    // Selection change will reposition the toolbar. Hide it for a few ms for a
                    // smoother transition.
                    widget.hideFloatingToolbar(HIDE_FLOATING_TOOLBAR_DELAY_MS);
                }
                Selection.setSelection(buffer,
                        buffer.getSpanStart(link),
                        buffer.getSpanEnd(link));
            }
            return true;
        } else {
            Selection.removeSelection(buffer);
        }
    }

    return super.onTouchEvent(widget, buffer, event);
}
 
Example 11
Source File: KeyboardUtil.java    From Android-Architecture with Apache License 2.0 4 votes vote down vote up
/**
 * 设置输入框的光标到末尾
 */
public static void setEditTextSelectionToEnd(EditText editText) {
    Editable editable = editText.getEditableText();
    Selection.setSelection((Spannable) editable,
            editable.toString().length());
}
 
Example 12
Source File: LongClickableLinkMovementMethod.java    From RichText with MIT License 4 votes vote down vote up
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
    int action = event.getAction();

    if (action == MotionEvent.ACTION_UP ||
            action == MotionEvent.ACTION_DOWN) {
        int x = (int) event.getX();
        int y = (int) event.getY();

        x -= widget.getTotalPaddingLeft();
        y -= widget.getTotalPaddingTop();

        x += widget.getScrollX();
        y += widget.getScrollY();

        Layout layout = widget.getLayout();
        int line = layout.getLineForVertical(y);
        int off = layout.getOffsetForHorizontal(line, x);

        LongClickableSpan[] link = buffer.getSpans(off, off, LongClickableSpan.class);

        if (link.length != 0) {
            long currTime = System.currentTimeMillis();
            LongClickableSpan l = link[0];
            int ls = buffer.getSpanStart(l);
            int le = buffer.getSpanEnd(l);
            // 判断点击的点是否在Image范围内
            ClickableImageSpan[] is = buffer.getSpans(ls, le, ClickableImageSpan.class);
            if (is.length > 0) {
                if (!is[0].clicked(x)) {
                    Selection.removeSelection(buffer);
                    return false;
                }
            } else if (off < layout.getOffsetToLeftOf(ls) || off > layout.getOffsetToLeftOf(le + 1)) {
                // 判断点击位置是否在链接范围内
                Selection.removeSelection(buffer);
                return false;
            }

            if (action == MotionEvent.ACTION_UP) {
                // 如果按下时间超过500毫秒,触发长按事件
                if (currTime - lastTime > MIN_INTERVAL) {
                    if (!l.onLongClick(widget)) {
                        // onLongClick返回false代表事件未处理,交由onClick处理
                        l.onClick(widget);
                    }
                } else {
                    l.onClick(widget);
                }
            } else {
                Selection.setSelection(buffer,
                        ls, le);
            }
            lastTime = currTime;
            return true;
        } else {
            Selection.removeSelection(buffer);
            return false;
        }
    }

    return super.onTouchEvent(widget, buffer, event);
}
 
Example 13
Source File: MongolTextView.java    From mongol-library with MIT License 4 votes vote down vote up
public void setSelection(int index) {
    Selection.setSelection(mTextStorage, index);
}
 
Example 14
Source File: TextViewLinkHandler.java    From chat21-android-sdk with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
    public boolean onTouchEvent(TextView widget, Spannable buffer,
                                MotionEvent event) {
        int action = event.getAction();

        if (action == MotionEvent.ACTION_UP ||
                action == MotionEvent.ACTION_DOWN) {
            int x = (int) event.getX();
            int y = (int) event.getY();

            x -= widget.getTotalPaddingLeft();
            y -= widget.getTotalPaddingTop();

            x += widget.getScrollX();
            y += widget.getScrollY();

            Layout layout = widget.getLayout();
            int line = layout.getLineForVertical(y);
            int off = layout.getOffsetForHorizontal(line, x);

            ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);

            if (link.length != 0) {
                if (action == MotionEvent.ACTION_UP) {
                    onLinkClick(link[0]);
//                    URLSpan[] linkUrlSpan = buffer.getSpans(off, off, URLSpan.class);
//                    if (linkUrlSpan[0].getURL().toString().startsWith(urlStartWith)) {
                        //onLinkClick(linkUrlSpan[0].getURL());
//                    }else {
//                        link[0].onClick(widget);
//                    }
                } else if (action == MotionEvent.ACTION_DOWN) {
                    Selection.setSelection(buffer,
                            buffer.getSpanStart(link[0]),
                            buffer.getSpanEnd(link[0]));
                }

                return true;
            } else {
                Selection.removeSelection(buffer);
            }
        }

        return super.onTouchEvent(widget, buffer, event);
    }
 
Example 15
Source File: MaskedEditText.java    From FormattEditText with Apache License 2.0 4 votes vote down vote up
private void formatMask(@NonNull Editable value) {
	InputFilter[] inputFilters = value.getFilters();
	value.setFilters(new InputFilter[0]);

	int indexInMask = 0;
	int indexInText = 0;
	int maskLength = 0;
	int inputLength = 0;
	boolean treatNextCharAsLiteral = false;
	boolean maskIsNotNumeric = false;

	Object selection = new Object();
	value.setSpan(selection, Selection.getSelectionStart(value), Selection.getSelectionEnd(value), Spanned.SPAN_MARK_MARK);

	while (indexInMask < mask.length()) {
		char charInMask = mask.charAt(indexInMask);
		if (!treatNextCharAsLiteral && isMaskChar(charInMask)) {
			// Found mask character, try to parse text
			maskIsNotNumeric |= charInMask != NUMBER_MASK;
			if (indexInText >= value.length()) {
				// Add trailing placeholders
				value.insert(indexInText, placeholder);
				value.setSpan(new PlaceholderSpan(), indexInText, indexInText + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
				++indexInText;
				++inputLength;
				++maskLength;
				++indexInMask;
			} else if (!matchMask(charInMask, value.charAt(indexInText))) {
				// Skip bad character in text
				value.delete(indexInText, indexInText + 1);
			} else {
				// Character in text is acceptable, go to next character in mask
				++indexInText;
				++inputLength;
				++maskLength;
				++indexInMask;
			}
		} else if (!treatNextCharAsLiteral && charInMask == ESCAPE_CHAR) {
			// Next character in mask must be escaped
			treatNextCharAsLiteral = true;
			++indexInMask;
		} else {
			// Found a literal or escaped character in mask
			value.insert(indexInText, String.valueOf(charInMask));
			value.setSpan(new LiteralSpan(), indexInText, indexInText + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			treatNextCharAsLiteral = false;

			++indexInText;
			++maskLength;
			++indexInMask;
		}
	}

	while (value.length() > maskLength) {
		int pos = value.length() - 1;
		value.delete(pos, pos + 1);
	}

	Selection.setSelection(value, value.getSpanStart(selection), value.getSpanEnd(selection));
	value.removeSpan(selection);

	value.setFilters(inputFilters);

	int newInputType = inputLength > 0
			? (maskIsNotNumeric
			? InputType.TYPE_CLASS_TEXT
			: InputType.TYPE_CLASS_NUMBER)
			: 0;
	if (getInputType() != newInputType)
		setInputType(newInputType);
}
 
Example 16
Source File: EditText.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * Convenience for {@link Selection#setSelection(Spannable, int, int)}.
 */
public void setSelection(int start, int stop) {
    Selection.setSelection(getText(), start, stop);
}
 
Example 17
Source File: Launcher.java    From LaunchEnr with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void clearTypedText() {
    mDefaultKeySsb.clear();
    mDefaultKeySsb.clearSpans();
    Selection.setSelection(mDefaultKeySsb, 0);
}
 
Example 18
Source File: DefaultMovementMethod.java    From PinView with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(TextView widget, Spannable text) {
    // It will mark the IMM as openable
    Selection.setSelection(text, 0);
}
 
Example 19
Source File: FabOverlapTextView.java    From materialup with Apache License 2.0 4 votes vote down vote up
/**
 * This is why you don't implement your own TextView kids; you have to handle everything!
 */
@Override
public boolean onTouchEvent(MotionEvent event) {
    if (!(text instanceof Spanned)) return super.onTouchEvent(event);

    Spannable spannedText = (Spannable) text;

    boolean handled = false;
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        pressedSpan = getPressedSpan(spannedText, event);
        if (pressedSpan != null) {
            pressedSpan.setPressed(true);
            Selection.setSelection(spannedText, spannedText.getSpanStart(pressedSpan),
                    spannedText.getSpanEnd(pressedSpan));
            handled = true;
            postInvalidateOnAnimation();
        }
    } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
        TouchableUrlSpan touchedSpan = getPressedSpan(spannedText, event);
        if (pressedSpan != null && touchedSpan != pressedSpan) {
            pressedSpan.setPressed(false);
            pressedSpan = null;
            Selection.removeSelection(spannedText);
            postInvalidateOnAnimation();
        }
    } else if (event.getAction() == MotionEvent.ACTION_UP) {
        if (pressedSpan != null) {
            pressedSpan.setPressed(false);
            pressedSpan.onClick(this);
            handled = true;
            postInvalidateOnAnimation();
        }
        pressedSpan = null;
        Selection.removeSelection(spannedText);
    } else {
        if (pressedSpan != null) {
            pressedSpan.setPressed(false);
            handled = true;
            postInvalidateOnAnimation();
        }
        pressedSpan = null;
        Selection.removeSelection(spannedText);
    }
    return handled;
}
 
Example 20
Source File: TextViewFixTouchConsume.java    From umeng_community_android with MIT License 4 votes vote down vote up
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
    int action = event.getAction();

    if (action == MotionEvent.ACTION_UP ||
            action == MotionEvent.ACTION_DOWN) {
        int x = (int) event.getX();
        int y = (int) event.getY();

        x -= widget.getTotalPaddingLeft();
        y -= widget.getTotalPaddingTop();

        x += widget.getScrollX();
        y += widget.getScrollY();

        Layout layout = widget.getLayout();
        int line = layout.getLineForVertical(y);
        int off = layout.getOffsetForHorizontal(line, x);

        ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);

        if (link.length != 0) {
            if (action == MotionEvent.ACTION_UP) {
                link[0].onClick(widget);
            } else if (action == MotionEvent.ACTION_DOWN) {
                Selection.setSelection(buffer,
                        buffer.getSpanStart(link[0]),
                        buffer.getSpanEnd(link[0]));
            }

            if (widget instanceof TextViewFixTouchConsume) {
                ((TextViewFixTouchConsume) widget).mlinkHit = true;
            }
            return true;
        } else {
            Selection.removeSelection(buffer);
            Touch.onTouchEvent(widget, buffer, event);
            return false;
        }
    }
    return Touch.onTouchEvent(widget, buffer, event);
}