Change button behaviour according to user input - java

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

Related

Why my app stops when I delete all from EditText?

I want to check if the value of EditText is greater than 5, I want the background of the edittext to become RED and it does so but stops when I delete the Text. Please help.
vibration.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) {
vibration.setBackgroundColor(Color.YELLOW);
}
#Override
public void afterTextChanged(Editable s) {
float numV = Float.parseFloat(vibration.getText().toString());
if(numV > 5){
vibration.setBackgroundColor(Color.RED);
}else{
return;
}
}
});
first check if the the value you are getting from EditText is not null.
if(!yourEditText.isempty)
{
//Do your work here
}
else{
//EditText is null}

How to disable button with multiple edit text using Textwatcher?

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.

Check if text in editText has changed

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

Android getText a text from EditText?

I'm adding a text in EditBox with setText code.After I'm changing this text into EditText and I want to get in a String value this text with getText.But this returning null.
My code:
EditText kullanilan = (EditText) findViewById(R.id.edt_kullanilacakSayi);
gunSayi = Double.toString(izinGun); // gunSayi is string value
kullanilan.setText(gunSayi);
String songunSayi=kullanilan.getText().toString();
I found a solution.
kullanilan.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) {
songunSayi=kullanilan.getText().toString();
}
});
}

dynamically change the length of String inside the EditText field in Android

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.

Categories

Resources