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.
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);
}
}
}
I have two editTexts. I want to test every time if the text has been changed and if it's the case I want to change the text of the second one too.
Here is what I've done :
TextWatcher fieldValidatorTextWatcherElec = new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
if (filterLongEnough1()) {
et_electricite_€.setText(String.valueOf(new BigDecimal(Double.parseDouble(et_electricite.getText().toString())*tarif).setScale(2, RoundingMode.HALF_UP).doubleValue()));
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
private boolean filterLongEnough1() {
return et_electricite.getText().toString().trim().length() > 0;
}
};
et_electricite.addTextChangedListener(fieldValidatorTextWatcherElec);
TextWatcher fieldValidatorTextWatcherElecTarif = new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
if (filterLongEnough()) {
et_electricite.setText(String.valueOf(new BigDecimal(Double.parseDouble(et_electricite_€.getText().toString())/tarif).setScale(2, RoundingMode.HALF_UP).doubleValue()));
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
private boolean filterLongEnough() {
return et_electricite_€.getText().toString().trim().length() > 0;
}
};
et_electricite_€.addTextChangedListener(fieldValidatorTextWatcherElecTarif);
The problem is: When I click for the first time it changes; when I try to do the same thing with the second editText the application doesn't move and after that, it crashes. Here's the errorlog:
E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 2057252)
E/MQSEventManagerDelegate: reportJEEvent error happened:android.os.TransactionTooLargeException: data parcel size 2057252 bytes
you can add an edit text listener. Put you logic on afterTextChanged
EditText answer = new EditText(this);
//second, we create the TextWatcher
TextWatcher textWatcher = 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) {
}
#Override
public void afterTextChanged(Editable editable) {
//here, after we introduced something in the EditText we get the string from it
String answerString = answer.getText().toString();
//and now we make a Toast
//modify "yourActivity.this" with your activity name .this
Toast.makeText(yourActivity.this,"The string from EditText is: "+answerString,0).show();
}
};
//third, we must add the textWatcher to our EditText
answer.addTextChangedListener(textWatcher);
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())
}
}
I am using an EditText field in my application.
EditText is for entering the ddns input:
e.g www.example.com/xxxx
I want to restrict the length of the ddns id to 30 characters after "/" character.
i.e after "/" character, what follows must be of maximum 30 characters
I want to do it dynamically and restrict user to not type more than 30 characters.
How can i do it.
You can try the below way to restrict the user to enter less than 30 character.
tf.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//processing part
}
});
A very fast and ugly answer would look something like this:
yourEditText.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.toString().contains('/') {
if(s.toString().split('/')[1].length() == 30) {
//By only working with the EditText:
InputMethodManager imm = (InputMethodManager)
getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
yourEditText.setFocusable(false);
yoruEditText.setEnabled(false);
}
}
}
#Override
public void afterTextChanged(Editable s) {
}});
//What i think is the best implementation, adding a TextView sitting on top of
//EditText with visibility set to GONE
yourEditText.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.toString().contains('/') {
if(s.toString().split('/')[1].length() == 30) {
//By working with EditText and a TextView
yourEditText.setVisibility(View.GONE);
yourTextView.setVisibility(View.VISIBLE);
yourTextView.setText(s);
}
}
}
#Override
public void afterTextChanged(Editable s) {
}});
In any case you want to add a textWatcher to your editText and change it accordingly.
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);
}
});