EditText setError() with icon but without Popup message - android

I want to to have some validation for my EditText wherein I want to show "" icon (that comes when you put editText.setError("blah blah")) but don't want the text in the popup displaying that "blah blah".
Is there any way to do it? One way is to create a custom layout which will show the image icon in the EditText. But is there any better solution?

Problem solved after a lot of research and permutations- (Also thanks to #van)
Create a new class that will extend EditText something like this-
public class MyEditText extends EditText {
public MyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void setError(CharSequence error, Drawable icon) {
setCompoundDrawables(null, null, icon, null);
}
}
Use this class as a view in your xml like this-
<com.raj.poc.MyEditText
android:id="#+id/et_test"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
Now in the third step, just set a TextWatcher to your custom text view like this-
et = (MyEditText) findViewById(R.id.et_test);
errorIcon = getResources().getDrawable(R.drawable.ic_error);
errorIcon.setBounds(new Rect(0, 0, errorIcon.getIntrinsicWidth(), errorIcon.getIntrinsicHeight()));
et.setError(null,errorIcon);
et.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
if(s.toString().length()>6){
et.setError("", null);
}else{
et.setError("", errorIcon);
}
}
});
where R.drawable.ic_error =
Keeping text null solves the problem
But if we keep only null in setError(null), this won't show the validation error; it should be null along with second param.

You dont need to create a new EditText class or change xml. The solution is very simple:
Edittext editText= (EditText) rootView.findViewById(R.id.email);
String str= editText.getText().toString();
if(str.equalsIgnoreCase("") ){
Drawable dr = getResources().getDrawable(R.drawable.error);
//add an error icon to yur drawable files
dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight());
editText.setCompoundDrawables(null,null,dr,null);
}

Sorry Rajkiran, but your solution is not working on Android 4.2 version. If I am trying to set null value for error, it is not even displayed. The solution I came up was to extend EditText and override setError method. No I have only error indicator without popup.
#Override
public void setError(CharSequence pError, Drawable pIcon) {
setCompoundDrawables(null, null, pIcon, null);
}

I have been dealing with the same problem. I wanted to use .setError() to my EditText when user insert null input. But I think the pop-out message is annoying, especially when you have more EditTexts.
My solution was naive and simple, but it worked on all devices I've tried so far.
I created my own class myEditText and just #Override this method:
#Override
public void setError(CharSequence error, Drawable icon) {
setCompoundDrawables(null, null, icon, null);
}
then use in layout.xml
<cz.project.myEditText
...
/>
and finally in my code
I put onFocusChangeListener to myEditText, so when someone clicks-in, the icon disappears.
myEditText input = (myEditText) findViewById(R.id.input);
input.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
input.setError(null);
});
if(val == null) input.setError("");
It works Exactly how I want = no pop-up message when .setError() is called on EditText.

To get only the error-icon without an error-message-popup only when setError("") is called (i.e. set an empty String as error-message) I use a custom EditText-class where I override setError(CharSequence, Drawable) like this:
#Override
public void setError(CharSequence error, Drawable icon) {
if (error == null) {
super.setError(null, icon);
setCompoundDrawables(null, null, null, null);
}
else if (error.toString().equals("")) setCompoundDrawables(null, null, icon, null);
else super.setError(error, icon);
}
Everything else stays the same:
Use setError(null) to get neither the icon nor the message-popup.
Use setError(errorMessage), where errorMessage is a String with length 1 at least, to get the icon and message-popup.

This is the very useful when you want to show the error messages for the edittext field when the user enter wrong information.this is very simply program only you have to use serError() method in the edittext.
Step 1:
Create button and implement onclickListener.
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
Step 2:
Validate the input fields and set the error in the input field.
if(edName.length()>3){
if(edNumber.length()>3){
Toast.makeText(getApplicationContext(), "Login success", Toast.LENGTH_SHORT).show();
}else{
edNumber.setError("Number Mininum length is 4");
}
}else{
edName.setError("Name Mininum length is 4");
}
Refer this link for more:http://velmuruganandroidcoding.blogspot.in/2014/08/set-error-message-in-edittext-android.html

Related

How to add a value to a Toast, from a Edittext (with button)

I searched the web, but couldn't find a solution. I found several codes but I have some problems to implement it in my code. Hope you guys know what I'm messing up here.
I'm creating an SMS app, where you choose from a spinner (which preloads
a txt) and you can continue the text from an edittextfield and press
the button to send the SMS. Working great but now I would like the toast to
contain what the user wrote in the field.I can create a normal Toast where I can write my own text. If you look at case 1 you can see where I wrote value_edittextfield (just so you can see where the value should be) and String nrforanvandare is the EditTextField.
I really hope there is a solution, because it would be so awesome.
spinneruse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0 :
skickatelBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
}
);
case 1 :
skickatelBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myMsgnruta = tele1txt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
String nrforanvandare = nrrutaforspinner.getText().toString();
sendMsg(theNumberr, myMsgnruta + nrforanvandare);
Toast.makeText(getActivity(), "value_Edittextfield. sent",
Toast.LENGTH_LONG).show();
}
}
);
break;
According to EditText you can use getText() to get the input text, which in turn returns Editable, which you can get with the default toString() method.
For example:
Toast.makeText(getApplicationContext(), myEditText.getText().toString(),
Length_LONG).show();
Here, I assumed that your EditText variable name is myEditText.
This should do it.
EDIT:
On a side note, why wouldn't using String nrforanvandare = nrrutaforspinner.getText().toString(); do the trick, given nrrutaforspinner is your EditText? If not, well, that's how you do it.

Keyboard mainactivity.this

I have three problems I want to learn how to make a customize keyboard and I found this site
http://www.fampennings.nl/maarten/android/09keyboard/index.htm
but there I have 3 problem about this keyboard.
First problem is that mainactivity isn't work at on key method unlike it was described.
private OnKeyboardActionListener mOnKeyboardActionListener = new OnKeyboardActionListener() {
#Override
public void onKey(int primaryCode, int[] keyCodes) {
// Get the EditText and its Editable
View focusCurrent = MainActivity.this.getWindow().getCurrentFocus();
if( focusCurrent==null || focusCurrent.getClass()!=EditText.class ) return;
EditText edittext = (EditText) focusCurrent;
Editable editable = edittext.getText();
other problem is that getSystemServise give error in Eclipse. I look to a lots of topic but every answers give different idea and I can't apply these ideas.
public void showCustomKeyboard( View v ) {
mKeyboardView.setVisibility(View.VISIBLE);
mKeyboardView.setEnabled(true);
if( v!=null ) ( (InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(v.getWindowToken(), 0);
}
// getSystemService Gives eRror
an other problem is that registeredittext method it take int resid but there is findViewById give error like here.
public void registerEditText(int resid) {
// Find the EditText 'resid'
EditText edittext= (EditText)findViewById(resid); // gives error
// Make the custom keyboard appear
edittext.setOnFocusChangeListener(new OnFocusChangeListener() {

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

Make EditText ReadOnly

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

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