Ive tried using TextWatcher, but if i create multiple TextWatchers(one for each EditText), the button enables when I start filling out any of the EditText.
Example:
public class MainActivity extends AppCompatActivity {
EditText numberOneEditText;
EditText numberTwoEditText;
EditText numberThreeEditText;
TextView sumTextView;
public void calculate(View view) {
String numberOneString = numberOneEditText.getText().toString();
String numberTwoString = numberTwoEditText.getText().toString();
String numberThreeString = numberThreeEditText.getText().toString();
double numberOneDouble = Double.parseDouble(numberOneString);
double numberTwoDouble = Double.parseDouble(numberTwoString);
double numberThreeDouble = Double.parseDouble(numberThreeString);
double sum = numberOneDouble + numberTwoDouble + numberThreeDouble;
sumTextView.setText(sum.getText().toString())
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numberOneEditText = findViewById(R.id.numberOneEditText);
numberTwoEditText = findViewById(R.id.numberTwoEditText);
numberThreeEditText = findViewById(R.id.numberThreeEditText);
sumTextView = findViewById(R.id.sumTextView);
}
}
Use TextWatcher. It will solve your problem:
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().trim().length()==0){
btn.setEnabled(false);
} else {
btn.setEnabled(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
}
});
This must solve your problem:
public class AppActivity extends Activity {
private EditText editText1;
private EditText editText2;
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
checkFieldsForEmptyValues();
}
#Override
public void afterTextChanged(Editable editable) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_activity);
editText1 = (EditText) findViewById(R.id.reg_password);
editText2 = (EditText) findViewById(R.id.reg_password2);
editText1.addTextChangedListener(textWatcher);
editText2.addTextChangedListener(textWatcher);
checkFieldsForEmptyValues();
}
private void checkFieldsForEmptyValues(){
Button btn = (Button) findViewById(R.id.btnId);
String s1 = editText1.getText().toString();
String s2 = editText2.getText().toString();
if (s1.length() > 0 && s2.length() > 0) {
btn.setEnabled(true);
} else {
btn.setEnabled(false);
}
}
}
Thanks.
Your text watcher should check that all three EditTexts have data (preferably also make sure that they are double, and display a label with an error message if otherwise)
Something like this:
TextWatcher watcher = 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) {
for (EditText et : new EditText[] {numberOneEditText,
numberTwoEditText, numberThreeEditText}) {
try {
Double.parseDouble(et.getText());
} catch (NumberFormatException e) {
// Disable button, show error label, etc.
button.setEnabld(false);
return;
}
}
//Enable buttton, hide error label if available
button.setEnabled(true);
}
};
}
numberOneEditText.addTextChangedListener(watcher);
numberTwoEditText.addTextChangedListener(watcher);
numberThreeEditText.addTextChangedListener(watcher);
You only have to declare one textwatcher which you assign to all edittexts. Then :
btn.setEnabled(!(str1.isEmpty || str2.isEmpty() || str3.isEmpty));
You could also directly check if it is a valid double and not enable if not.
EditText numberOneEditText;
EditText numberTwoEditText;
EditText numberThreeEditText;
TextView sumTextView;
public void calculate(View view) {
boolean isValid = true;
String numberOneString = numberOneEditText.getText().toString();
String numberTwoString = numberTwoEditText.getText().toString();
String numberThreeString = numberThreeEditText.getText().toString();
if(numberOneString.trim().isEmpty ||numberTwoString.trim().isEmpty()
|| numberThreeString.trim().isEmpty()){
isValid = false;}
if(isValid){
double numberOneDouble = Double.parseDouble(numberOneString);
double numberTwoDouble = Double.parseDouble(numberTwoString);
double numberThreeDouble = Double.parseDouble(numberThreeString);
double sum = numberOneDouble + numberTwoDouble + numberThreeDouble;
sumTextView.setText(sum.getText().toString())
}
}
Related
I was creating user interface where user have to enter the mobile number in EditText. maxLength of that EditText is 10. Now I want when 10 digits entered by the user the keyboard automatically get hide. How to implement this. I already searched on google but not a single code worked for me. Below is my XML & Fragment code.
XML Code
<EditText
android:id="#+id/editTextPhone"
style="#style/EditText"
android:background="#drawable/border_design"
android:inputType="phone"
android:hint="#string/editText_phone_hint"
android:maxLength="10"
android:drawableLeft="#drawable/phone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Fragment Code
public class MobileNumberFragment extends Fragment {
String mobileNumber;
editTextNumber = (EditText) view.findViewById(R.id.editTextPhone);
protected boolean isValidNumber(String registerMobileNumber) {
if (registerMobileNumber != null && registerMobileNumber.length() == 10) {
return true;
}
return false;
}
private void SendOtp() {
mobileNumber = editTextNumber.getText().toString().trim();
if (!isValidNumber(mobileNumber)) //Condition so that no edit-text will remain empty
{
editTextNumber.setError("Enter the Valid Mobile Number");
editTextNumber.requestFocus();
return;
} else {
buttonSendOtp.setText("Processing...");
}
}
You can force Android to hide the virtual keyboard using the InputMethodManager, calling hideSoftInputFromWindow, passing in the token of the window containing your focused view.
// Check if no view has focus:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtName = (EditText)findViewById(R.id.txtName);
txtName.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.toString().length() == 10){
HideKeyboardFormUser();
}
}
});
}
public void HideKeyboardFormUser(){
View view = getCurrentFocus();
InputMethodManager hideKeyboard = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
hideKeyboard.hideSoftInputFromWindow( view.getWindowToken(), 0);
}
}
This will force the keyboard to be hidden in all situations. In some cases you will want to pass in InputMethodManager.HIDE_IMPLICIT_ONLY as the second parameter to ensure you only hide the keyboard when the user didn't explicitly force it to appear (by holding down menu).
editTextNumber.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.toString().length() >= 10) {
editTextNumber.setVisibility(View.GONE);
} else {
editTextNumber.setVisibility(View.VISIBLE);
}
}
});
You need to add a TextWatcher listener to the EditText, and hide the keyboard once the length reached 10.
editTextNumber = (EditText) view.findViewById(R.id.editTextPhone);
editTextNumber.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) {
if (s.length() == 10){
hideSoftKeyboard(requireActivity());
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
public void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
View currentFocus = activity.getCurrentFocus();
if (inputMethodManager != null) {
IBinder windowToken = activity.getWindow().getDecorView().getRootView().getWindowToken();
inputMethodManager.hideSoftInputFromWindow(windowToken, 0);
inputMethodManager.hideSoftInputFromWindow(windowToken, InputMethodManager.HIDE_NOT_ALWAYS);
if (currentFocus != null) {
inputMethodManager.hideSoftInputFromWindow(currentFocus.getWindowToken(), 0);
}
}
}
Here I first attempt to login with blank values and it successfully displayed the errors. Now I am looking to hide the error "email required" when I type a value to the email textfield. I want to remove the error message "email required" when I type the first key in the email textfield
. How can I implement such a feature to this code?
textInputEmail = (TextInputLayout) findViewById(R.id.text_input_email);
textInputPassword = (TextInputLayout) findViewById(R.id.text_input_password);
login =(Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!ValidateEmail() || !ValidatePassword())
{
return;
}
String inputs = "Email : "+ textInputEmail.getEditText().getText().toString().trim();
inputs +="\n";
inputs +="Password : "+ textInputPassword.getEditText().getText();
Toast.makeText(MainActivity.this,inputs, Toast.LENGTH_SHORT).show();
}
});
}
private Boolean ValidateEmail() {
String emailPattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
String emailInput = textInputEmail.getEditText().getText().toString().trim();
if (emailInput.isEmpty()) {
textInputEmail.setError("Email required");
return false;
} else if (!emailInput.matches(emailPattern)) {
textInputEmail.setError("Invalid Email");
return false;
} else {
textInputEmail.setError(null);
textInputEmail.setErrorEnabled(false);
return true;
}
}
You can use TextWatcher to when text is changed remove the error
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
textInputEmail.setError(null);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
just set error text to empty string
editText.setError("", null);
You have to add text watcher for edit text. Then you hide Required error.
Check below example for better understanding.
<android.support.design.widget.TextInputLayout
android:id="#+id/text_input_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/Theme.AppCompat">
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword"
android:padding="12dp">
</android.support.design.widget.TextInputLayout>
Then in your activity/fragment
private EditText passwordEditText;
private TextInputPassword textInputPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Initializing views */
passwordEditText = (EditText) findViewById(R.id.password);
/* Set Text Watcher listener */
passwordEditText.addTextChangedListener(passwordWatcher);
textInputPassword = (TextInputLayout)
findViewById(R.id.text_input_password);
}
private final TextWatcher passwordWatcher = new TextWatcher() {
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) {
if (s.length() == 0) {
textInputPassword.setErrorEnabled(true);
textInputPassword.setError("Password Required");
} else{
textInputPassword.setErrorEnabled(false);
textView.setText("You have entered : " + passwordEditText.getText());
}
}
};
You could control the visibility of the error like. I'm asuming you can get the reference to the error label and it's stored in a variable called errorLabel
#Override
public void onClick(View v) {
errorLabel.setVisibility( validateEmail() && validatePassword() );
}
I am trying to disable my button if my input edit texts are empty. I am using text watcher for this. To test it out , i have only tried with only two edit texts to start.
However, my button stays enabled no matter what.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_profile);
fnameInput = findViewById(R.id.et_firstname);
lnameInput = findViewById(R.id.et_lastname);
numberInput = findViewById(R.id.et_phone);
emailInput = findViewById(R.id.et_email);
nextBtn = findViewById(R.id.btn_next);
fnameInput.addTextChangedListener(loginTextWatcher);
lnameInput.addTextChangedListener(loginTextWatcher);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchNextActivity();
}
});
}
Text watcher method
private TextWatcher loginTextWatcher = 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) {
String firstNameInput =firstNameInput.getText().toString().trim();
String lastNameInput = lastNameInput.getText().toString().trim();
// tried doing it this way
nextBtn.setEnabled(!firstNameInput.isEmpty() && !lastNameInput.isEmpty());
//What i've also tried
if(firstNameInput.length()> 0 &&
lastNameInput.length()>0){
nextBtn.setEnabled(true);
} else{
nextBtn.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
I expect the button to be disabled if one or all inputs are empty and enabled when all input fields are filled out.
create a method check all condition there like
private void checkTheConditions(){
if(condition1 && condition2)
nextBtn.setEnabled(true)
else
nextBtn.setEnabled(false)
}
call this method from afterTextChanged(Editable s) method
Let us consider this case for 2 EditTexts only as for now.
define 2 global CharSequence as below
CharSequence fName="";
CharSequence lName="";
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_profile);
fnameInput = findViewById(R.id.et_firstname);
lnameInput = findViewById(R.id.et_lastname);
numberInput = findViewById(R.id.et_phone);
emailInput = findViewById(R.id.et_email);
nextBtn = findViewById(R.id.btn_next);
fnameInput.addTextChangedListener(textWatcher);
lnameInput.addTextChangedListener(textWatcher2);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchNextActivity();
}
});
}
then you have to define different textwatcher for each of your Edittext
then inside each of these textWatcher assign values to CharSequence defined above
private TextWatcher textWatcher = 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) {
fName=s;
validate(); //method to enable or disable button (find method below)
}
#Override
public void afterTextChanged(Editable s) {
}
};
now textWatcher2
private TextWatcher textWatcher2 = 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) {
lName=s;
validate(); //method to enable or disable button (find method below)
}
#Override
public void afterTextChanged(Editable s) {
}
};
now write validate method
void validate(){
if (fName.length()>0 && lName.length()>0){
nextBtn.setEnabled(true);
}else {
nextBtn.setEnabled(false);
}
}
Oh! You did a small mistake. Use OR condition instead of AND. So your code should be
nextBtn.setEnabled(!firstNameInput.isEmpty() || !lastNameInput.isEmpty());
And TextWatcher will only notify when you will manually change the inputs of EditText. So TextWatcher will not wark at starting. So at first in onCreate method you should manually check those EditText feilds.
Edit:
Android new DataBinding library is best suitable for this purpose.
This part of my program is supposed to be a user input field for the quantity of an item to purchase. What I'm unable to do is to make it so when the program finally runs on the emulator and I change the textfield number in the EditText, named "etxtQuantity" in my case, the number I use is ignored and it reverts to using the default entry. Also my if statement isn't working like I expect either, it accepts everything.
private void setupAddRecordButton() {
Button button = (Button) findViewById(R.id.btnAddCart);
button.setOnClickListener(new View.OnClickListener() {
final TextView countText = (TextView) findViewById(R.id.txtAddCartCount);
EditText quantity = (EditText) findViewById(R.id.etxtQuantity);
String quantity2 = quantity.getText().toString();
final TextView text2 = (TextView) findViewById(R.id.txtQuantityCheck);
#Override
public void onClick(View v) {
if (! quantity2.equals(".") || quantity2.equals("") || quantity2.equals("-")) {
count++;
long newId = myDb.insertRow("GTX 950", 140, quantity2);
myDb.getRow(newId);
countText.setText("Successfully added " + count + " Times");
}
else
{
text2.setText("Quantity needed!");
}
}
});
}
initailize your edit text in onCreate() callback function of your activity and use String quantity2 = quantity.getText().toString(); in onClick() function of your button
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText quantity = (EditText) findViewById(R.id.etxtQuantity);
Button button = (Button) findViewById(R.id.btnAddCart);
TextView text2 = (TextView) findViewById(R.id.txtQuantityCheck);
TextView countText = (TextView) findViewById(R.id.txtAddCartCount);
button.setOnClickListener(new View.OnClickListener() {
String quantity2 = quantity.getText().toString();
#Override
public void onClick(View v) {
if (! quantity2.equals(".") || quantity2.equals("") ||quantity2.equals("-")) {
count++;
long newId = myDb.insertRow("GTX 950", 140, quantity2);
myDb.getRow(newId);
countText.setText("Successfully added " + count + " Times");
}
else
{
text2.setText("Quantity needed!");
}
}
});
}
please move the this line
String quantity2 = quantity.getText().toString();
inside the onClick()
Try to use
quantity .addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
quantity2=charSequence.toString();
if (! quantity2.equals(".") || quantity2.equals("") || quantity2.equals("-")) {
count++;
long newId = myDb.insertRow("GTX 950", 140, quantity2);
myDb.getRow(newId);
countText.setText("Successfully added " + count + " Times");
}
else
{
text2.setText("Quantity needed!");
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
I'm writing a simple app in Android.
I've encountered this problem: I've two EditText and a Button. The value of one EditText must be a multiple of the other one EditText.
When the user insert a value in the first EditText and then press the button, the other EditText should show the value calculated with the user input.
This should be possible in other verse, too.
Like a simple unit converter. When I insert value1 in EditText1 and press convert the app must show the converted value in EditText2, but if I insert a value2 in EditText2 and press convert button the app must show the converted value in EditText1.
My problem is: how can I recognize in which EditText there are last user-input?
public void convert(View view) {
EditText textInEuro = (EditText) findViewById(R.id.euroNumber);
EditText textInDollar = (EditText) findViewById(R.id.dollarNumber);
if (toDollar) {
String valueInEuro = textInEuro.getText().toString();
float numberInEuro = Float.parseFloat(valueInEuro);
// Here the conversione between the two currents
float convertedToDollar = unit * numberInEuro;
// set the relative value in dollars
textInDollar.setText(Float.toString(convertedToDollar));
}
if (toEuro) {
String valueInDollar = textInDollar.getText().toString();
float numberInDollar = Float.parseFloat(valueInDollar);
//Here the conversione between the two currents
float convertedToEuro = numberInDollar / unit;
//set the relative value in dollars
textInEuro.setText(Float.toString(convertedToEuro));
}
}
This is the code written. I've thinked to use OnClickListener..but it isn't a good idea..
You can add a TextWatcher to your two EditText in order to know which one has been updated last.
public class MainActivity extends Activity {
EditText dollar;
EditText euro;
private static final int EURO = 0;
private static final int DOLLAR = 1;
private int lastUpdated = DOLLAR;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dollar = findViewById(R.id.dollar);
euro = findViewById(R.id.euro);
dollar.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
lastUpdated = DOLLAR;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
euro.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
lastUpdated = EURO;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void convert(View view) {
switch (lastUpdated) {
case EURO:
//Do work for euro to dollar
break;
case DOLLAR:
//Do work for dollar to euro
break;
default:
break;
}
}
}
I have a different way in mind,you can try this to achieve what you want:
when user comes first on activity,let him edit any edit text fields.(one is being filled,the other will be disabled until he pressed button)
let him click button
once the results are filled and he wants to edit one of the edittext,other edittext would be automatically empty
lets say you have editText_1 and editText_2,and your button is button_1.Also take a boolean variable called convertBoolean and make it false as default.
Now,
editText_1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(convertBoolean==false){
editText_2.setEnabled(false); //disable other edittext when one is being edited
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
#Override
public void afterTextChanged(Editable s) {
String s1=editText_1.getText().toString().trim();
String s2=editText_2.getText().toString().trim();
if(!s1.equals("") && !s2.equals("") && convertBoolean==true){
//of both are filled, empty second edittext
editText_2.setText("");
convertBoolean=false;
}
if(editText_1.getText().toString().trim().equals("") && convertBoolean==false){
editText_2.setEnabled(true);
}
}
});
editText_2.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(convertBoolean==false){
editText_1.setEnabled(false); //disable other edittext when one is being edited
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
#Override
public void afterTextChanged(Editable s) {
String s1=editText_1.getText().toString().trim();
String s2=editText_2.getText().toString().trim();
if(!s1.equals("") && !s2.equals("") && convertBoolean==true){
//of both are filled, empty first edittext
editText_1.setText("");
convertBoolean=false;
}
if(editText_2.getText().toString().trim().equals("") && convertBoolean==false){
editText_1.setEnabled(true);
}
}
});
button_1.setOnClickListener(new OnClickListener(){
public void onClick(){
convertBoolean=true;
editText_1.setEnabled(true);
editText_2.setEnabled(true);
}
});