I can disable EditText, but then the user will simply unable to change the text. The behaviour I am trying to implement is that, if the user tries to type something (or any other changing method such as pasting), showing a message like "You cannot edit this text because of something.".
At first, I thought I could show the message using TextWatcher, but there seems to be no way to cancel the change. How can I achieve the behaviour I am looking for? The only way I could think is the following really dirty way.
Have a backup of the text of the EditText. When EditText is changed,
if isReverting is false, show the message and set isReverting to
true. If isReverting is true, just set it to false. Set the backup
to the EditText.
A TextWatcher will fullfill the need in your case . Do the validation inside afterTextChange(). Below is an example.
et_Name.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 s) {
String input=s.toString();
if(s.length()>4){
Toast.makeText(MainActivity.this, "You can only input 4 letters",
Toast.LENGTH_SHORT).show();
String old=input.substring(0,4);
et_Name.setText(old);
et_Name.setSelection(old.length());
}
}
});
Your solution will work great. You can also just store the unmodifiable value in a variable and simply change the text back in afterTextChanged if the value is different.
<EditText
android:id="#+id/amount"
android:inputType="number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:editable="false"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp" />
You can make EditText non editable by using the following property programatically
editText.setEnabled(false);
no need of textChangeListner
I have an EditText that I want to use so people can input a short bio.
So I am trying to make it so it's fixed at, for example, a box that is 4 lines high. I don't want it to "scale" or "shift" with the input -- I'm trying to make it a fixed box of a fixed number of lines with word-wrap.
I did try adding lines="4" and maxLines="4" and inputType="textCapSentences|textMultiLine" but it doesn't quite seem to be right. When I set text, it appears in the middle of the EditText (and not the upper left), and it seems to let me hit enter a whole lot so I can have a word in the first row and then a character like 20 rows down.
Current XML:
<EditText
android:background="#00ff00"
android:id="#+id/editTextId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lines="4"
android:maxLines="4"
android:inputType="textCapSentences|textMultiLine"
android:gravity="left|top"/>
I'm using a background of green so I can more easily see it for now. Right now this lets you type as much as you want, but I want to limit it to the space as given.
There is in no built code to achieve what you need. But here is a workaround -
private String enteredText;
edtText.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 s) {
if (edtText.getLineCount() > 4) {
edtText.setText(enteredText);
edtText.setSelection(edtText.getText().length()); //This statement is to move the cursor at the end of the text otherwise it'll be moved to the start of the text.
}
else {
enteredText = edtText.getText().toString();
}
}
});
Hope this helps !!
to fix the centered text issue add:
android:gravity="top|left"
To prevent the user from inputting more then 4 lines, you'll need to do it by code.
Add a TextWatcher to the EditText, and check the number of lines after each text-change:
TextWatcher textWatcher = new TextWatcher() {
onTextChanged(CharSequence s, int start, int before, int count) {
// Check number of lines here
}
};
editText.addTextChangedListener(textWatcher);
Just add this attribute to your edittext
android:inputType="textMultiLine"
This code is in a layout file.
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textInputLayoutMobile"
>
<EditText
android:inputType="number"
android:id="#+id/mobileNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="10"
android:hint="Mobile Number" />
</android.support.design.widget.TextInputLayout>
This is Java code.
TextInputLayout textInputLayoutMobile = (TextInputLayout)findViewById(R.id.textInputLayoutMobile);
textInputLayoutMobile.setErrorEnabled(true);
textInputLayoutMobile.setError("This field is required");
Current behaviour: When we click on the field, it shows, "This field is required". Also when we start typing in the field, this message does not go away.
Desired behaviour: When we click for the first time, it should not show, "This field is required". When we move to another field after touching this field and without entering any data, it should show, "This field is required". Also when we start typing in the field, this message should go away.
I think you must use text change listener
edit.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) {
//set error
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
and on his method to set your desire output.. hope to help you!
I believe the error is that those two lines of code are used while retrieving the textInputLayoutMobile from your layout (probably in onCreate). So the view is set to always display this error message.
textInputLayoutMobile.setErrorEnabled(true);
textInputLayoutMobile.setError("This field is required");
I suppose those two lines should be moved from this point and set there where you should validate the textInputLayoutMobile input and deciding that the validation is wrong, e.g. in an onClick callback or listener. Additionally when your input is validated to true then set textInputLayoutMobile.setErrorEnabled(false);
See an example here: http://code.tutsplus.com/tutorials/creating-a-login-screen-using-textinputlayout--cms-24168
I think you need take id="#+id/mobileNumber", set the widget and than try something like that
your_widget.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
if (yourwidget.getText().toString().length() == 0) {
yourwidget.setError("This field is required");}
else etc...
You could use this control on a "next" button or something like that (save button etc) insted of use that on the field directly (sorry for my english)
I think you need to take the reference of EditText and not the TextInputLayout.
Try
EditText editText = (EditText)findViewById(R.id.mobileNumber);
editText.setError("This field is required");
I am creating an email form and would like to have text in an EditText that cannot be deleted. On the screenshot below, the To could not be deleted.
If anyone has suggestions on how to achieve the above, it would be great - Thanks.
My current code for the To EditText box:
<EditText
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="0dp"
android:hint="#string/email_to" >
</EditText>
The problem is android:hint text dissappears when the user starts to text, and android:text can be deleted by the user.
How do we have text that cannot be deleted? Thanks.
Note:
Also, I would like to note that I have a method that clears text using a clear button - this works fine - but I am hoping that it would not delete the fixed text (If I got that implemented!).. Here`s the code for that:
private void clearForm(ViewGroup group)
{
for (int i = 0, count = group.getChildCount(); i < count; ++i) {
View view = group.getChildAt(i);
if (view instanceof EditText) {
((EditText)view).setText("");
}
if(view instanceof ViewGroup && (((ViewGroup)view).getChildCount() > 0))
clearForm((ViewGroup)view);
}
}
SOLUTION:
Managed a roundabout way of doing this.. I created a TextView and EditText within a nested Linear Layout. I turned off the border in the EditText using android:background="#00000000".
I created an xml file in the drawable folder, and refered to this in the relevant linear layout like this: android:background="#drawable/customxml"
You can do it by using Text Watcher listener.
You can keep text in edittext by checking length of edittext.
For example
editText.setText("To") // it mean have lenght 2
And Than in method afterTextChanged, check if text in editText is has been deleted (with check length of text in editText)
This is for complete example code:
editText.setText("To");
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 s) {
if(s.length < 2){
editText.setText("To")//set editext with "To" again like has been initialized
editText.setSelection(editText.getText().length)// to make cursor in end of text
}
}
});
Hope this help!
To get the visual appearance you want, include a horizontal LinearLayout containing a text view and an EditView. Turn off the border around the EditView (there's an attribute that does that (I think it's android:shadowColor) ) Play around with margins and padding to get them to be adjacent to each other. Set the background color on the linear layout to put a border around the combined pair.
I wouldn't worry much about efficiency. You aren't nesting very deeply. The biggest challenge is going to be getting it to look like a single view.
Edit: Another thought. If that doesn't work, you could make the "To" a drawable, and set it using the android:drawableLeft attribute.
Add TextView to the right side of EditText in LinearLayout with horizontal orientation or RelativeLayout with android:layout_toRightOf="#id/YourTextView"
I want to make a read-only EditText view. The XML to do this code seems to be android:editable="false", but I want to do this in code.
How can I do this?
Please use this code..
Edittext.setEnabled(false);
If you setEnabled(false) then your editText would look disabled (gray, etc). You may not want to change the visual aspect of your editor.
A less intrusive way would be to use setFocusable(false).
I believe that this answers your question closer to your initial intent.
In XML use:
android:editable="false"
As an example:
<EditText
android:id="#+id/EditText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:editable="false" />
This works for me:
EditText.setKeyListener(null);
editText.setInputType(InputType.TYPE_NULL);
As per the docs this prevents the soft keyboard from being displayed. It also prevents pasting, allows scrolling and doesn't alter the visual aspect of the view. However, this also prevents selecting and copying of the text within the view.
From my tests setting setInputType to TYPE_NULL seems to be functionally equivalent to the depreciated android:editable="false". Additionally, android:inputType="none" seems to have no noticeable effect.
android:editable="false" has been deprecated. Therefore you cant use it to make the edit text readonly.
I have done this using the bellow solution. Here I have used
android:inputType="none"
android:textIsSelectable="true"
android:focusable="false"
Give it try :)
<EditText
android:id="#+id/et_newsgpa_university"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="#string/hint_educational_institute"
android:textSize="#dimen/regular_text"
android:inputType="none"
android:textIsSelectable="true"
android:focusable="false"
android:maxLines="1"
android:imeOptions="actionNext"/>
The best is by using TextView instead.
editText.setEnabled(false);
editText.setFilters(new InputFilter[] { new InputFilter() {
public CharSequence filter(CharSequence src, int start, int end,
Spanned dst, int dstart, int dend) {
return src.length() < 1 ? dst.subSequence(dstart, dend) : "";
}
} });
This will give you uneditable EditText filter. you first need to put the text you want on the editText field and then apply this filter.
writing this two line is more than enough for your work.
yourEditText.setKeyListener(null);
yourEditText.setEnabled(false);
set in XML
android:inputType="none"
Try using
editText.setEnabled(false);
editText.setClickable(false);
Try overriding the onLongClick listener of the edit text to remove context menu:
EditText myTextField = (EditText)findViewById(R.id.my_edit_text_id);
myTextField.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return true;
}
});
android:editable
If set, specifies that this TextView has an input method. It will be a textual one unless it has otherwise been specified. For TextView, this is false by default. For EditText, it is true by default.
Must be a boolean value, either true or false.
This may also be a reference to a resource (in the form #[package:]type:name) or theme attribute (in the form ?[package:][type:]name) containing a value of this type.
This corresponds to the global attribute resource symbol editable.
Related Methods
If you just want to be able to copy text from the control but not be able to edit it you might want to use a TextView instead and set text is selectable.
code:
myTextView.setTextIsSelectable(true);
myTextView.setFocusable(true);
myTextView.setFocusableInTouchMode(true);
// myTextView.setSelectAllOnFocus(true);
xml:
<TextView
android:textIsSelectable="true"
android:focusable="true"
android:focusableInTouchMode="true"
...
/>
<!--android:selectAllOnFocus="true"-->
The documentation of setTextIsSelectable says:
When you call this method to set the value of textIsSelectable, it sets the flags focusable, focusableInTouchMode, clickable, and longClickable to the same value...
However I had to explicitly set focusable and focusableInTouchMode to true to make it work with touch input.
Use this code:
editText.setEnabled(false);
editText.setTextColor(ContextCompat.getColor(context, R.color.black);
Disabling editText gives a read-only look and behavior but also changes the text-color to gray so setting its text color is needed.
this is my implementation (a little long, but useful to me!):
With this code you can make EditView Read-only or Normal. even in read-only state, the text can be copied by user. you can change the backgroud to make it look different from a normal EditText.
public static TextWatcher setReadOnly(final EditText edt, final boolean readOnlyState, TextWatcher remove) {
edt.setCursorVisible(!readOnlyState);
TextWatcher tw = null;
final String text = edt.getText().toString();
if (readOnlyState) {
tw = new TextWatcher();
#Override
public void afterTextChanged(Editable s) {
}
#Override
//saving the text before change
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
// and replace it with content if it is about to change
public void onTextChanged(CharSequence s, int start,int before, int count) {
edt.removeTextChangedListener(this);
edt.setText(text);
edt.addTextChangedListener(this);
}
};
edt.addTextChangedListener(tw);
return tw;
} else {
edt.removeTextChangedListener(remove);
return remove;
}
}
the benefit of this code is that, the EditText is displayed as normal EditText but the content is not changeable. The return value should be kept as a variable to one be able revert back from read-only state to normal.
to make an EditText read-only, just put it as:
TextWatcher tw = setReadOnly(editText, true, null);
and to make it normal use tw from previous statement:
setReadOnly(editText, false, tw);
This worked for me, taking several of the suggestions above into account. Makes the TextEdit focusable, but if user clicks or focuses, we show a list of selections in a PopupWindow. (We are replacing the wacky Spinner widget). TextEdit xml is very generic...
public void onCreate(Bundle savedInstanceState) {
....
fEditState = (EditText) findViewById(R.id.state_edit);
fEditState.setLongClickable(false);
fEditState.setKeyListener(null);
fEditState.setFocusable(true);
fEditState.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus)
{
showStatesPopup();
}
}
});
fEditState.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0)
{
showStatesPopup();
}
});
....
}
private void showStatesPopup()
{
// fPopupWindowStates instantiated in OnCreate()
if (!fPopupWindowStates.isShowing()) {
// show the list view as dropdown
fPopupWindowStates.showAsDropDown(fEditState, -5, 0);
}
}
This was the only full simple solution for me.
editText.setEnabled(false); // Prevents data entry
editText.setFocusable(false); // Prevents being able to tab to it from keyboard
As android:editable="" is deprecated,
Setting
android:clickable="false"
android:focusable="false"
android:inputType="none"
android:cursorVisible="false"
will make it "read-only". However, users will still be able to paste into the field or perform any other long click actions. To disable this, simply override onLongClickListener().
In Kotlin:
myEditText.setOnLongClickListener { true }
suffices.
My approach to this has been creating a custom TextWatcher class as follows:
class ReadOnlyTextWatcher implements TextWatcher {
private final EditText textEdit;
private String originalText;
private boolean mustUndo = true;
public ReadOnlyTextWatcher(EditText textEdit) {
this.textEdit = textEdit;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (mustUndo) {
originalText = charSequence.toString();
}
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
if (mustUndo) {
mustUndo = false;
textEdit.setText(originalText);
} else {
mustUndo = true;
}
}
}
Then you just add that watcher to any field you want to be read only despite being enabled:
editText.addTextChangedListener(new ReadOnlyTextWatcher(editText));
I had no problem making EditTextPreference read-only, by using:
editTextPref.setSelectable(false);
This works well when coupled with using the 'summary' field to display read-only fields (useful for displaying account info, for example). Updating the summary fields dynamically snatched from http://gmariotti.blogspot.com/2013/01/preferenceactivity-preferencefragment.html
private static final List<String> keyList;
static {
keyList = new ArrayList<String>();
keyList.add("field1");
keyList.add("field2");
keyList.add("field3");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
for(int i=0;i<getPreferenceScreen().getPreferenceCount();i++){
initSummary(getPreferenceScreen().getPreference(i));
}
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory pCat = (PreferenceCategory) p;
for (int i = 0; i < pCat.getPreferenceCount(); i++) {
initSummary(pCat.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
private void updatePrefSummary(Preference p) {
if (p instanceof ListPreference) {
ListPreference listPref = (ListPreference) p;
p.setSummary(listPref.getEntry());
}
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
//editTextPref.setEnabled(false); // this can be used to 'gray out' as well
editTextPref.setSelectable(false);
if (keyList.contains(p.getKey())) {
p.setSummary(editTextPref.getText());
}
}
}
Set this in EdiTextView xml file
android:focusable="false"
in java file:
Edittext.setEnabled(false);
in xml file:
android:editable="false"
These 2 lines makes ur edittext selectable and at the same time not editable (it doesn't even show the soft keyboard):
editText.setInputType(InputType.TYPE_NULL);
editText.setTextIsSelectable(true);