Make EditText ReadOnly - android

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);

Related

error message displaying continuously in TextInputLayout

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");

Detect if content of EditText was changed by user or programmatically?

I would need a way to detect if the EditText has been changed by the user typing something or by the app changing the text programmatically. Any standard way of doing this? I guess I could always do something hackish like unsetting the TextWatcher before setText() and setting it back again afterwards, but there's got to be a better way of doing this... right?
I tried checking if the EditText is focused in the TextWatcher, but that was of little help since the EditTexts gets focused "semi-randomly" anyway when scrolling...
Background
I have a ListView with EditTexts in every listitem. I've sorted out the basic problem of storing the values for the EditTexts for reuse when the user scrolls.
I also have a TextWatcher that sums up the values in all EditTexts and displays the sum when the user edits the content of any of the EditTexts.
The problem is that when I'm scrolling the list and my custom adapter is reentering the stored values in the EditTexts on bindView(), that also triggers the TextWatchers afterTextChanged() method, causing the scrolling to lag because the summing-up-function is triggered.
This sorted itself out a long time ago, but for anyone who finds their way here looking for an answer, here's what I did:
I ended up setting the Tag of the EditText to some arbitrary value right before I'm about to change it programmatically, and changing the value, and then resetting the Tag to null. Then in my TextWatcher.afterTextChanged() method I check if the Tag is null or not to determine if it was the user or the program that changed the value. Works like a charm!
Something like this:
edit.setTag( "arbitrary value" );
edit.setText( "My Text Value" );
edit.setTag(null);
and then
public void afterTextChanged(Editable s) {
if( view.getTag() == null )
// Value changed by user
else
// Value changed by program
}
The accepted answer is perfectly valid, but I have another approach;
#Override
public void onTextChanged(CharSequence charSequence,
int start, int before, int count) {
boolean userChange = Math.abs(count - before) == 1;
if (userChange) {
}
}
It works by checking if the change was a single character.
This is not a fool-proof solution as copy-paste operations might be missed, and non-user changes of a single character will also be missed.
Depending on your use case, this might be a viable solution.
One thing that helped to me is having boolean canListenInput field. Use it inside of watcher.
email.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
if (canListenInput) {
emailChanged = true;
}
}
});
Clear it before changing text programmatically. Set it inside of onAttachedToWindow, (after state) restoration:
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
canListenInput = true;
}
Depending on your use case (e.g. you are auto-populating this field when the user types into another field), you can also check if the view has focus, e.g.:
textView.doAfterTextChanged {
val isValueChangedByUser = textView.hasFocus()
// ...
}
I have created some extension methods to tackle this scenario
inline fun TextView.runTaggingCode(block: () -> Unit) {
this.setTag(R.string.tag_text_id, "set_from_code")
block()
this.setTag(R.string.tag_text_id, null)
}
fun TextView.isTaggedForCode() = this.getTag(R.string.tag_text_id) != null
where I have defined the R.string.tag_text_id as below
<string name="tag_text_id" translatable="false">dummy</string>
Now where I to use these methods, I will simply change my code as below,
override fun beforeTextChanged(
s: CharSequence, start: Int, count: Int,
after: Int,
) {
if (textView.isTaggedForCode()) {
return
}
textView.runTaggingCode {
// your logic here
}
}
But in case you don't want to change the same text view text, in it own TextWatcher you can also see the answer
You can do this by adding:
private String current = "";
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(!s.toString().equals(current)){
[your_edittext].removeTextChangedListener(this);
//Format your string here...
current = formatted;
[your_edittext].setText(formatted);
[your_edittext].setSelection(formatted.length());
[your_edittext].addTextChangedListener(this);
}

Adding EditText fields on view when typing on a EditText

I want to create EditTextFields dynamically on depending the condition. Condition is that if I start typing on first EditTextField it will create one more EditTextField in the bottom and will create the third EditTextField when i start typing on second one. Similarly i want to delete the bottom text if there is no text in the upper EditTextField. Thanks.
Use a parent view, like a ScrollView that you know you can add a flexible about of content to. Then use a TextWatcher a/k/a a text change listener. You could then create a new text view which you would add to the ScrollView if text was typed into the EditText field.
For neatness I'd probably create a custom TextView class that housed this text change listener and replication check. Here's example of how you could add a TextView
//instance variable
private LinearLayout containerLayout;
private newTextViewCreated = false;
//initialize your conatinerLayout before you use it
//and create your first edit text field
public void onCreate(Bundle savedInstaceState){
containerLayout = (LinearLayout)findViewById(R.id.conatinerLinearLayout);
createEditText();
}
private void createEditText(){
EditText editText = new editText(this);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(count > 0 && !newTextViewCreated){
createEditText();
newTextViewCreated = true;
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
//TODO Auto-generated method stub
}
});
containerLayout.addView(editText);
}
I didn't test this out, I'm writing it now but here's what I'm thinking. Read the description of how a TextWatcher works so you understand the inner methods. You're going to have to play with the conditionals but what you're doing is listening for a change in the number of characters entered and then making a recursive call to create an additional view when chars are added to each text view. I use a boolean flag to show when a view has been created so we don't add one each time the char is changed. I moved outside the createEditText method based on your comment. If you made your own EditText class you could just add a method that would set/get the status of whether this TextView had spanwed another. To remove you would just add a delete condition that would remove the view from the linear layout.
User TextWatcher
Implement your Activity with TextWatcher and override method
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
Show / Hide them in your layout if you know the total amount of editText fields needed or add them programatically like so:
EditText myET = new EditText(MyActivity.this);
myET.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
LayoutContentView.addView(myET);
Then check:
if (myET.getText().toString().trim().equals(""))
{
//Don't Show
}else{
//SHOW
}
SO question could help:https://stackoverflow.com/a/6792359/350421
EditText toAdd = new EditText(this);
list.add(toAdd);

Android: Restrict user from selecting other than autocompletion suggestions?

I have provided an AutoCompleteTextView to show suggestions to the user. Based on the item selected by the user, I am getting the ID of the item and using it in data base side. Now my problem is to force the user to make selection only from AutoCompleteTextView (i.e. user should not enter his own text). It is a client requirement. How to do this?
Here's a pretty straightforward solution:
You can create a variable to store the selected value by setting setOnItemClickListener in your AutoCompleteTextView. Then you can null that value whenever a user types in the field by adding a TextWatcher to it. Finally, you can validate your variable is not null before continuing.
String my_var; //keep track!
AutoCompleteTextView tv = (AutoCompleteTextView) layout.findViewById(R.id.tv);
tv.setAdapter(my_adapter);
tv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
my_var = my_adapter.getItem(position).toString();
}
});
/**
* Unset the var whenever the user types. Validation will
* then fail. This is how we enforce selecting from the list.
*/
tv.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) {
my_var = null;
}
#Override
public void afterTextChanged(Editable s) {}
});
I happened to need such a requirement for a project I am working on, and I though I'll share you guys the way I implemented the required.
I added a on focus change listener for the auto-complete text view and checked when the user has focus changed focus from the auto-complete, and handled the situation straight forward.
autoTextViewCountry.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean b) {
if(!b) {
// on focus off
String str = autoTextViewCountry.getText().toString();
ListAdapter listAdapter = autoTextViewCountry.getAdapter();
for(int i = 0; i < listAdapter.getCount(); i++) {
String temp = listAdapter.getItem(i).toString();
if(str.compareTo(temp) == 0) {
return;
}
}
autoTextViewCountry.setText("");
}
}
});
So my implementation is: if the typed text doesn't exist in the array adapter then on focus changed empty the text view, and later on when continuing to next stage of say registration, check if this text view is empty or not.
Hope this approach helps somebody.
Happy coding.
NiceAutoCompleteTextView will give you the ability to check whether a selection was made from the drop-down popup, by invoking isSelectionFromPopup()
Just add this property to your AutoCompleteTextView.
android:focusable="false"
My Code looks like:
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/menu"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Mode">
<AutoCompleteTextView
android:id="#+id/mode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false"
/>
</com.google.android.material.textfield.TextInputLayout>
On Java Side:
AutoCompleteTextView mode = findViewById(R.id.mode);
final List<String> modeList = new ArrayList();
modeList.add("YEARLY");
modeList.add("HALF-YEARLY");
modeList.add("QUARTER-YEARLY");
modeList.add("MONTHLY");
mode.setAdapter(new ArrayAdapter(getApplicationContext(),R.layout.list_item,modeList));
To get the Text of AutoCompleteTextView:
mode.getText().toString()
Ok I assume you would like to limit the input of the user to the texts contained in the list of items listed in the suggest box.
For instance if you have:
One
Two
Three
then the user could only type for the first character "O" and "T".
And so on according to the text entered before.
To achieve this you can utilize the setFilters method of TextView:
editBox = (TextView) findViewById(R.id.editBox);
editBox.setFilters(getFilters());
editBox.addTextChangedListener(this);
editBox.setOnFocusChangeListener(this);
Additionally you would probably need the text change listener and focus listener to react and update the filtered list when a new character is entered ... plus to update the filter.
Here is an example of decimal number filter I have used on a project:
protected InputFilter[] getFilters()
{
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter()
{
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend)
{
// limit input to digits and decimal / thousand separator only
// in case thousand separator is pressed, change it to decimal
// separator instead
String output = "";
if (number.isFocused())
{
for (int i = start; i < end; i++)
{
char c = source.charAt(i);
if (isDecimalOrThousandSeparator(c))
{
output = output + Character.toString(decimalSeparator);
}
else if (Character.isDigit(c))
{
output = output + Character.toString(c);
}
}
return output == "" ? null : output;
}
return null;
}
};
return filters;
}
A simple solution would be to just check if the current input is one of the items in the adapter. You can do it like this:
val AutoCompleteTextView.isValid: Boolean
get() {
for (i in 0 until adapter.count) {
if (adapter.getItem(i) == text.toString()) {
return true
}
}
return false
}
here is the another solution for this proAutoCompleteTextView.Validator to ensure the valid values. Validator is invoked when edit text looses focus.
autoCompleteTextView.validator = object : AutoCompleteTextView.Validator {
override fun isValid(text: CharSequence?): Boolean {
return optionsList.contains(text.toString())
}
override fun fixText(invalidText: CharSequence?): CharSequence {
return ""
}
}
Where optionsList is list of valid values.
I was having the same requirement, so here is my implementation:
autoCompleteTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
autoCompleteTextView.showDropDown();
}
});
In the xml set focusable=false and focusableInTouchMode=false.
Happy coding
In order to have a non editable variation of the AutoCompleteTextView, you should disable user input in the AutoCompleteTextView. That can be achieved by setting android:inputType="none" on the AutoCompleteTextView.

How do you gray out a "Submit" button when specific EditText boxes are empty?

Regarding an Android app I am creating:
I have three EditText boxes that need to be filled with numbers/strings. I have a submit button that will start a series of calculations.
IF any box is empty and submit is pressed, the app crashes. I have tried to do this with try-catch statement, but it is not working out. I simply want to disable the button until three boxes have numbers. I know there is a way to setEnabled(false) I think? Or is there a better way? Will this grey out the button? Or is that an unrelated function to setEnabled?
Try this solution.
EditText edit1;
EditText edit2;
EditText edit3;
View button;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Your initialization code...
TextWatcher watcher = new LocalTextWatcher();
edit1.addTextChangedListener(watcher);
edit2.addTextChangedListener(watcher);
edit3.addTextChangedListener(watcher);
updateButtonState();
}
void updateButtonState() {
boolean enabled = checkEditText(edit1)
&& checkEditText(edit2)
&& checkEditText(edit3);
button.setEnabled(enabled);
}
private boolean checkEditText(EditText edit) {
return Integer.getInteger(edit.getText().toString()) != null;
}
private class LocalTextWatcher implements TextWatcher {
public void afterTextChanged(Editable s) {
updateButtonState();
}
void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
void onTextChanged(CharSequence s, int start, int before, int count) {
}
}
You should disable the button by default in the XML so that the user cannot hit the button by accident. After this you need to look at your fields and insure all of them have data before the submission.
You could do this, or you could just have submit run a quick check on all the fields and insure none of them are equal to "".
Basically look like this (If you want to ignore hiding the button and just handle processing after the check)
if (!((t1.getText().toString.compareTo("") == 0) && (t2.getText().toString.compareTo("")==0) ...))
{
Do stuff
}
else
{
Toast message here
}
Otherwise you can just have a "watcher" like the above poster mentioned.
You can also use this check
boolean checkEditText(EditText editText) {
return editText.getText().toString().trim().equals("");
}
Hi i have tried above code and changed the function to given below for it to work.
private boolean checkEditText(EditText edit) {
return ((edit.getText().toString()).length() >0 );
}

Categories

Resources