Button button = findViewById(R.id.button); EditText editText = findViewById(R.id.editText); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int selectionStart = editText.getSelectionStart(); Toast.makeText(getApplicationContext(), "Selection start: " + selectionStart, Toast.LENGTH_SHORT).show(); } });
EditText editText = findViewById(R.id.editText); editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(10) { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if (dend > edit.getSelectionStart()) { int selectedLength = edit.getSelectionEnd() - edit.getSelectionStart(); int sourceLength = end - start; int newLength = dest.length() + sourceLength - selectedLength; if (newLength <= 10) { return null; } else { int newCharCount = 10 - dest.length() + selectedLength; if (newCharCount > 0 && newCharCount <= sourceLength) { return source.subSequence(start, start + newCharCount); } else { return ""; } } } else { return null; } } } });Both of these examples use the android.widget package.