I've found many questions about setting an edit text to readOnly or to editable, but all of them only work for some specific scenarios. I need the following functionality:
An Edittext widget which is editable should be set to readonly programmatically. When it is readonly, it shouldn't be possible to input data, but the current content should be selectable to copy. The same field should set back to editable to the same state as before, so allow input and select the text for copy/paste.
This is my current code:
if (readOnly)
{
_text.setTextColor(Color.GRAY);
_keyListener = _text.getKeyListener();
_text.setKeyListener(null);
}
else
{
_text.setTextColor(_foreground);
if (_keyListener != null)
{
_text.setKeyListener(_keyListener);
}
_text.setFocusable(true);
}
I already tried the following methods:
setTextIsSelectable()
in the readonly part. This enables selection of text in the readonly field. But if I change it back to editable, the field is still only selectable.I think I forgot to set some kind of Listener or property. Maybe one of you knows which one that is.
Edit:
Tried the following:
Disabling of EditText in android
But it only works as long as I won't use the setTextIsSelectable()
to make the readonly text selectable. If I set this value and switch back to editable, the field is only selectable, but not editable.
Thanks
Use this parameters android:textIsSelectable="true"
android:inputType="none"
(android:editable
is deprecated)
or programmatically
editText.setInputType(InputType.TYPE_NULL);
editText.setTextIsSelectable(true);
If this is dont work you can try something custom, at first use android:textIsSelectable="true"in your xml, after define two methods
private void disableEditText() {
editText.setInputType(InputType.TYPE_NULL);
disabled = true;
}
private void enableEditText() {
editText.setInputType(InputType.TYPE_CLASS_TEXT);
disabled = false;
}
and open keyboard every time when text is nor disabled and use click to editText
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
if (!disabled) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
}
}
});
And don't forget to define boolean disabled
Hope this is help you