This is one of my Edit text in the application
<EditText
android:id="@+id/etFolder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="/pictures"
android:ems="10" >
When it appear at first time it comes with "/pictures"
User can change the text and enter another word. but how to prevent deleting "/" of Edit text.
user can delete all other text but should not allow to delete first character.
How can I achieve this behavior ?
You can also use android:background="@null" . Edit: The TextView 's editable param does make it editable (with some restrictions). If you set android:editable="true" you can access the TextView via the D-pad, or you could add android:focusableInTouchMode="true" to be able to gain focus on touch.
To disable an EditText while keeping this properties, just use UI. setReadOnly(myEditText, true) from this library. If you want to replicate this behaviour without the library, check out the source code for this small method.
Defines an edit control belonging to the EDIT class. It creates a rectangular region in which the user can type and edit text. The control displays a cursor when the user clicks the mouse in it. The user can then use the keyboard to enter text or edit the existing text.
You can use the attribute style="@style/your_style" that is defined for any widget. The attribute parent="@android:style/Widget. EditText" is important because it will ensure that the style being defined extends the basic Android EditText style, thus only properties different from the default style need to be defined.
Kotlin example. You can do like this:
editText.addTextChangedListener(object: TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (editText.length() < 5 || !editText.text.startsWith("+998 ")) {
editText.setText("+998 ")
editText.setSelection(editText.length());
}
}
})
Based on ralphgabb's answer, this overcomes the problem of the caret ending up in the middle of the prefix when you do a rapid delete:
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable editable) {
String prefix = "+63";
int count = (editable == null) ? 0 : editable.toString().length();
if (count < prefix.length()) {
editText.setText(prefix);
/*
* This line ensure when you do a rapid delete (by holding down the
* backspace button), the caret does not end up in the middle of the
* prefix.
*/
int selectionIndex = Math.max(count + 1, prefix.length());
editText.setSelection(selectionIndex);
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With