I want to create a login page, I used EditText to insert user info. I want to check EditText to see if it is Empty Invisible login Button, when inserted any character with user visible Login Button.
I tried the code shown below, but it did not not work for me :
//Show Login Button
String login_phoneString = login_PhoneText.getText().toString().trim();
if (login_phoneString.isEmpty()) {
login_image.setVisibility(View.INVISIBLE);
} else {
login_image.setVisibility(View.VISIBLE);
}
When EditText is empty, the button is invisible, and when set character in EditText again the login button is not shown.
How can I fix this problem ?
You want to show/hide the Login button base on the text of EditText so you need to listen for changing in EditText by use TextWatcher.
Use this code inside onCreate() method
login_PhoneText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
String login_phoneString = login_PhoneText.getText().toString().trim();
if (login_phoneString.isEmpty()) {
login_image.setVisibility(View.INVISIBLE);
} else {
login_image.setVisibility(View.VISIBLE);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
Using trim()
if(et.getText().toString().trim().length() == 0) //empty
Using TextUtils
if(TextUtils.isEmpty(et.getText().toString().trim()) //Empty
Using isEmpty()
if(et.getText().toString().isEmpty()) //Empty
EDIT
You can do this :
//Show Login Button
String login_phoneString = login_PhoneText.getText().toString().trim();
if (TextUtils.isEmpty(login_phoneString) {
login_image.setVisibility(View.INVISIBLE);
} else {
login_image.setVisibility(View.VISIBLE);
}
Try to check like this way
EditText edt = (EditText) findViewById(R.id.edittext);
String abc = edt.getText().toString();
if (abc.matches("")) {
Toast.makeText(this, "enter something", Toast.LENGTH_SHORT).show();
login_image.setVisibility(View.INVISIBLE);
return;
}
else
{
login_image.setVisibility(View.VISIBLE);
}
String login_phoneString = login_PhoneText.getText().toString().trim();
if (login_phoneString.equals("")) {
login_image.setVisibility(View.GONE);
} else {
login_image.setVisibility(View.VISIBLE);
}
Use View.GONE instead of INVISIBLE. when INVISIBLE it is still clickable.
Use TextUtils.isEmpty():
if (TextUtils.isEmpty(yourEditText.getText().toString())) {
//Empty
} else {
//Not empty
}
Related
I have an android phone using googles keyboard. On any EditText field in any other app if I use the swipe method to enter text in, it adds a space after each word. However, I have written my own app and when I use the swipe method to enter text on my EditText field it does NOT add a space sothewordsbleedtogether. This is very annoying.
I have an AlertDialog with a linear view added. On that linear view there is a text EditText. Here is my code to create the EditText and add it to the view:
final EditText titleBox = new EditText(this);
titleBox.setInputType(InputType.TYPE_TEXT_FLAG_AUTO_CORRECT |
InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES |
InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE);
titleBox.setHint("Title");
layout.addView(titleBox);
Any ideas why its not adding spaces in between my words?
This was marked as a possible duplicate, but that question was about not allowing the first character to be a space....Im asking about allowing a space after words that are entered via a keyboard swipe.
Update
Here is the entire method of similar page, its having the same issue, its slightly less complex then the initial page I was troubleshooting. This one doesn't even have a LinearLayout associated:
private void addBudget(final Budget budget) {
EditText taskEditText = new EditText(this);
taskEditText.setId(R.id.add_budget_text);
taskEditText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
String dialogTitle = "Add budget";
final AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle(dialogTitle)
.setMessage("What do you want to call this budget?")
.setView(taskEditText)
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// final String task = ;
SQLiteDatabase db = mHelper.getWritableDatabase();
Budget lBudget = new Budget();
if (budget != null) {
lBudget = budget;
}
EditText taskEditText = (EditText) findViewById(R.id.add_budget_text);
lBudget.title = String.valueOf(taskEditText.getText());
// Init custom budget object //new Budget(){{ title=task; id = budgetID;}}
int retId = mHelper.saveBudget(db, lBudget);
db.close();
int retRow = updateUI(retId);
mTaskListView.smoothScrollToPosition(retRow);
}
})
.setNegativeButton("Cancel", null)
.create();
// Handle done on soft keyboard
taskEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
int result = actionId & EditorInfo.IME_MASK_ACTION;
if (result == EditorInfo.IME_ACTION_DONE) {
dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
return true;
}
return false;
}
});
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
dialog.show();
}
I didnt know if you got solved, i just had the same problem today and found a way to solve it.
I saw a "extrange" performance of the swipe, sometimes it showed the "blankspace" and sometimes not.
The way i found to check if it was shown and if it didnt, add it, was this:
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) {
checkCancel();
int compare = count-before;
if(compare>1){
String text = editText.getText().toString();
String lastChar = (text.substring(text.length()-1,text.length()));
if(!lastChar.equals(" ")){
String plus = text+" ";
editText.setText(plus);
editText.setSelection(editText.getText().length());
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
} );
You can see, onTextChanged can use the variables "before" and "count" and if the compare (difference between last word and current one) is more than 1, it's a word entered by Swipe. Then you can check if the "blankspace" is shown, and if not, just add it and perfom anything you want with it.
Hope it helps!
Could you try this? Add the filter into the editText. I used it for enter code on my app.
EditText et = (EditText) findViewById(R.id.edit_text);
et.setFilters(new InputFilter[] {
new InputFilter() {
#Override
public CharSequence filter(CharSequence charSequence, int start, int end, Spanned spanned, int start, int end {
if(charSequence.equals("")){
return charSequence;
}
if(charSequence.toString().matches("[a-zA-Z ]+")){
return charSequence;
}
return "";
}
}
});
So I uninstalled the google keyboard and reinstalled and I changed the build to release. One of those two things fixed it.
I'm trying to use a toggle button to switch between English -> Morse code and Morse code -> English. At this moment, I have to press the toggle button everytime I want the inputted data to be converted and this is not good. I want the toggle button only to be pressed once as desired to select to what it wants to translate to, and then while the user inputs data into the txt field, it will translate it as the user inputs data. Is this possible? And will this cause the app to lag?
If this will lag I'd like something else then.
A switch like the toggle button, to again choose to which one it needs to translate to. And then use to button to convert. This is somewhat possible now, but I need to click on the toggle button to translate, while I want to select the convert button to translate, and the toggle button to choose between English -> Morse code and Morse code -> English.
Here is some code I have for the toggle button:
final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleEnMo_Button);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// to English
Toast.makeText(MainActivity.this, toggle.getText(), Toast.LENGTH_SHORT).show();
if (edit_convert.getText().length() != 0) {
morseCode.setEnInput(edit_convert.getText().toString());
String txtToEnglish = morseCode.getEnInput();
morseCode.setMorseInput(morseCode.toEnglish(txtToEnglish));
String txtToMorse = morseCode.getMorseInput();
txtEnglish.setText(txtToEnglish);
txtMorse.setText(txtToMorse);
} else {
txtEnglish.setText("Text field empty");
}
} else {
// to Morse
Toast.makeText(MainActivity.this, toggle.getText(), Toast.LENGTH_SHORT).show();
if (edit_convert.getText().length() != 0) {
morseCode.setEnInput(edit_convert.getText().toString());
String txtToEnglish = morseCode.getEnInput();
morseCode.setMorseInput(morseCode.toMorse(txtToEnglish));
String txtToMorse = morseCode.getMorseInput();
txtEnglish.setText(txtToEnglish);
txtMorse.setText(txtToMorse);
} else {
txtEnglish.setText("Text field empty");
}
}
}
});
And the code I use for radio buttons and convert button which works:
button_convert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// show radio button text
int selectId = radioMorseGroup.getCheckedRadioButtonId();
radioMorseButton = (RadioButton) findViewById(selectId);
if (selectId == R.id.toEnglish) {
Toast.makeText(MainActivity.this,
radioMorseButton.getText(), Toast.LENGTH_SHORT).show();
// to english
if (edit_convert.getText().length() != 0) {
morseCode.setEnInput(edit_convert.getText().toString());
String txtToEnglish = morseCode.getEnInput();
morseCode.setMorseInput(morseCode.toEnglish(txtToEnglish));
String txtToMorse = morseCode.getMorseInput();
txtEnglish.setText(txtToEnglish);
txtMorse.setText(txtToMorse);
} else {
txtEnglish.setText("Text field empty");
}
} else if (selectId == R.id.toMorse) {
// to morse
Toast.makeText(MainActivity.this,
radioMorseButton.getText(), Toast.LENGTH_SHORT).show();
if (edit_convert.getText().length() != 0) {
morseCode.setEnInput(edit_convert.getText().toString());
String txtToEnglish = morseCode.getEnInput();
morseCode.setMorseInput(morseCode.toMorse(txtToEnglish));
String txtToMorse = morseCode.getMorseInput();
txtEnglish.setText(txtToEnglish);
txtMorse.setText(txtToMorse);
} else {
txtEnglish.setText("Text field empty");
}
}
}
});
I believe you are asking about intercepting user input as they type into a text field. You can use a TextWatcher. Here's some sample code that demonstrates this.
EditText mInputEt;
public void onCreate(Bundle savedInstanceState){
...
mInputEt.addTextChangedListener(mMyTextWatcher);
}
private TextWatcher mMyTextWatcher = 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) {
//take user input here and do something with it, like your translations
}
#Override
public void afterTextChanged(Editable s) {
}
};
Now to your question regarding lag, it shouldn't lag as long as all your intensive operations are executed in the background, off the main thread.
been looking for a previous answer for this but can't seem to find an android version of it...
I'm making a login page for an app, and I've got 3 input fields (First name, last name, email) and a text watcher to tell the user if there's an error in their input ((e.g. nothing there/too long/not a valid email). I'm trying to make the log in button disabled until no errors are showing, but I can't seem to sort it. I'm very new to android, just been working from scraps of tutorials here and there really... I've tried setting a boolean for each input value that sets to false when the input is bad/true when it's acceptable, and something to check if all 3 are true or not to enable/disable the button but that doesn't seem to work...
In the emulator, the button doesn't disable at all and I've got warnings that the booleans I made are always true even though I've given instances to make them false, and defined them as false at the start...
Here's my java class at the moment:
public class Login extends Activity implements OnClickListener, TextWatcher {
EditText firstName;
EditText lastName;
EditText eMail;
ImageButton Begin;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initialiseUI();
}
private void initialiseUI() {
eMail = (EditText)findViewById(R.id.edit_email);
eMail.addTextChangedListener(this);
firstName= (EditText)findViewById(R.id.edit_firstname);
firstName.addTextChangedListener(this);
lastName= (EditText)findViewById(R.id.edit_surname);
lastName.addTextChangedListener(this);
Begin= (ImageButton) findViewById(R.id.Beginbutton);
Begin.setOnClickListener(this);
}
boolean name=false;
boolean surname=false;
boolean email=false;
boolean isEmailValid(CharSequence eMail) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(eMail)
.matches();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
public void afterTextChanged(Editable s) {
Is_Valid_Email(eMail);
Is_Valid_Name(firstName);
Is_Valid_Surname(lastName);
Is_Login_Valid();
}
public void Is_Valid_Name(EditText firstName) {
if (firstName.getText().toString().trim().isEmpty()){
firstName.setError("Enter Name");
name=false;}
else if (firstName.getText().toString().length()>20){
firstName.setError("Name too long!");
name=false;}
else if (firstName.getText().toString().length()>1){
firstName.setError(null);
name=true;}
}
public void Is_Valid_Surname(EditText lastName){
if (lastName.getText().toString().trim().equalsIgnoreCase("")){
lastName.setError("Enter Surname");
surname=false;}
else if (lastName.getText().toString().length()>20){
lastName.setError("Surname too long!");
surname=false;}
else if (lastName.getText().toString().length()>1){
lastName.setError(null);
surname=true;}
}
public void Is_Valid_Email(EditText eMail) {
if (eMail.getText().toString().trim().equalsIgnoreCase("")) {
eMail.setError("Enter e-mail");
email=false;}
else if (!isEmailValid(eMail.getText().toString())) {
eMail.setError("Invalid Email Address");
email=false;}
else if (isEmailValid(eMail.getText().toString())) {
email=true;}
}
public void Is_Login_Valid() {
if (name=true){
if (surname=true){
if (email=true){
Begin.setEnabled(true);
}
else if (email=false){
Begin.setEnabled(false);
}
}
else if(surname=false){
Begin.setEnabled(false);
}
}
else if (name=false){
Begin.setEnabled(false);
}
}
/** Called when the user clicks the Login button */
public void onClick(View v) {
Intent intent = new Intent(Login.this, question_1.class);
startActivity(intent);
}
}
Please check setClickable(false)
http://developer.android.com/reference/android/view/View.html#setClickable%28boolean%29
I wouldn't use variables for check status. Have you tried what happens when a screen rotation? This might be chaos.
I recommend you to check your status everytime the text changes:
public void Is_Login_Valid() {
if(Is_Valid_Name(firstName) && Is_Valid_Surname(lastName) && Is_Valid_Email(eMail)){
Begin.setEnabled(true);
}else{
Begin.setEnabled(false);
}
I removed the name, surname, email booleans & Is_Login_Valid terms entirely and copied the acceptable conditions from Is_Valid_Name, Is_Valid_Surname and Is_Valid_Email into an if statement within the button's onClick term as below, and it seems to work fine now:
public void onClick(View v) {
if ((firstName.getText().toString().length() >= 1)
&& (firstName.getText().toString().length() < 20)
&& (lastName.getText().toString().length() >= 1)
&& (lastName.getText().toString().length() < 20)
&& (isEmailValid(eMail.getText().toString())))
{Intent intent = new Intent(Login.this, question_1.class);
startActivity(intent);}
else{ //TODO Login failed animation or popup
}
}
I have around 5 edittexts.When i click submit button,it has to check whether all fields are entered or not.Along with it if any value is not entered,the focus has to go to that desired edittext.If there are many editexts empty,then the focus has to go in top down order.I have used seterror method but when i type in that editext the error msg is not going.After entering values the focus is not going to the next edittext.how to solve this issue?
caseno,dateloss,policy_rep,reg_book,Dri_lic are the different editexts used.I have written code for one editext below
caseno.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasfocus)
{
if(!hasfocus && caseno.getText().length()==0)
{
new Handler().postDelayed(new Runnable()
{
#Override
public void run() {
//ev2.clearFocus();
dateloss.clearFocus();
policy_rep.clearFocus();
reg_book.clearFocus();
Dri_lic.clearFocus();
caseno.requestFocus();
caseno.setError("Enter this field");
}
}, 100);
}
}
});
btnsubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(caseno!=null||dateloss!=null||policy_rep!=null||reg_book!=null||Dri_lic!=null)
{
Send_reportclaim_Async reportsync=new Send_reportclaim_Async();
reportsync.execute();
}
}
});
Android provides a setError() method for this:
if(edttxtDescription.getText().toString().trim().equals(""))
{
edttxtDescription.setError("Please provide description");
}
Define a method to check whether your EditTexts have valid data:
private boolean validateEditTexts()
{
boolean valid = true;
if(edttxtDescription.getText().toString().trim().equals(""))
{
edttxtDescription.setError("Please provide description");
valid = false;
}
// Similarly check all your EditTexts here and set the value of valid
......
......
return valid;
}
To validate all your EditTexts, call validateEditTexts() which will return true or false accordingly.
btnsubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(validateEditTexts()){
Send_reportclaim_Async reportsync=new Send_reportclaim_Async();
reportsync.execute();
}
}
});
Try this. This will work.
Check this:
for(EditText edit : editTextList){
if(TextUtils.isEmpty(edit.getText()){
// EditText is empty
}
}
Maintain array of EditText references: Like
EditText[] allEts = { caseno, dateloss, policy_rep, reg_book, Dri_lic };
Write the below code in onClick of submit button:
for (EditText editText : allEts) {
String text = editText.getText().toString();
if (text.length() == 0) {
editText.setError("enter this field");
editText.requestFocus();
break;
}
}
And, implement addTextChangedListener for all edittexts to clear the error after entering the text.
caseno.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
Editable text = caseno.getText();
if (caseno.getError() != null && text != null
&& text.length() > 0) {
caseno.setError(null);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
Use this on your button click
if(!textView1.toString().isEmpty() && !textView2.toString().isEmpty() && ...)
{
............
}
1) create this method
public static boolean isNullOrEmpty(String input) {
return input == null || input.isEmpty();
}
2) send data to it for validation
boolean answer = isNullOrEmpty(editText.gettext().toString());
btnsubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(TextUtils.isEmpty(caseno.getText().toString()))
{
caseno.requestFocus();
Toast.makeText(getApplicationContext(),"Enter the required fields", Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(dateloss.getText().toString()))
{
dateloss.requestFocus();
Toast.makeText(getApplicationContext(),"Enter the required fields", Toast.LENGTH_LONG).show();
return;
}
}
Currently this setup is working for me...Thnks those who answered
I know that there are quite some questions out here regarding this question. But non of them have the answer that I'm looking for.
I've got 7 ET inside a ScrollView. When I start the application no ET has focus because I've added the following two lines to my overall layout:
android:focusable="true"
android:focusableInTouchMode="true"
When I click on an ET the softkeyboard is shown, which I want, then I set the value (let say 20). I press a '2' followed by a '0' and then press the back button. At this point the keyboard disappears, but the focus stays. I would like to clear the focus too when pressing the back button to hide the keyboard.
Because when the focus is cleared the layout of the ET is set like I want.
They all have about the some code, which is:
// Right Cable
RightCable = (EditText) findViewById (R.id.RightCable);
RightCable.setRawInputType(Configuration.KEYBOARD_12KEY);
RightCable.setOnFocusChangeListener(FocusChanged);
RightCable.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if(RightCable.isFocused()){
LengthRightCable = Double.parseDouble(RightCable.getText().toString());
Calculate();
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().matches("")) {
RightCable.setText("0.00");
Selection.setSelection(RightCable.getText(), 0, 4);
}
}
});
I use a focus listener to change the input of the ET to a number like 5.00 instead of 0.
OnFocusChangeListener FocusChanged = new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
EditText et = (EditText) v;
et.setSelection(0, et.getText().length());
if(!hasFocus){
String userInput = et.getText().toString();
int dotPos = -1;
for (int i = 0; i < userInput.length(); i++) {
char c = userInput.charAt(i);
if (c == '.') {
dotPos = i;
}
}
if (dotPos == -1){
et.setText(userInput + ".00");
} else if(userInput.length() < 5) {
if ( userInput.length() - dotPos == 1 ) {
et.setText(userInput + "00");
} else if ( userInput.length() - dotPos == 2 ) {
et.setText(userInput + "0");
}
}
}
}
};
Just override `onBackPressed()`
method in your activity and check condition for Edittext
focus before run
super.onBackPressed();
#Override
public void onBackPressed() {
if( et_search.isFocused()){
et_search.clearFocus();
}else {
super.onBackPressed();
}
}
For this you have to take the onTouchListener on the parent layout of the Layout File. on the TouchListener you have to code to hide the Keyboard when click outside the EditText. Please follow following XML Layout and Java class to resolve this issue.
Please follow the follow the following url to resolve this issue http://amitthaperandroidquery.blogspot.com/2011/10/remove-keyboard-after-click-outside.html