how to use afterTextChanged to reduce an amount inside a textview - java

I am trying to reduce an amount set on a TextView using aftetTextChanged. To achieve this I am doing the following inside my framgnet
TextWatcher code
editTextDiscount.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) {
}
#Override
public void afterTextChanged(Editable editable) {
Double damageCost = 0d;
String decDE = txtDamageEstimate.getText().toString().trim();
decDE = decDE.replace("£", "");
Double decDeResults = Double.valueOf((String) (decDE));
if (!TextUtils.isEmpty(editTextDiscount.getText())) {
damageCost = editTextDiscount.getCleanDoubleValue();
}
txtDiscount.setText(" "+nf.format(-damageCost));
txtDamageEstimate.setText(nf.format(decDeResults-damageCost));
}
});
This works however it reduced x2 the amount inputed and when I backspace my input, it wont reset to its original amount e.g if it was 20.00 and I enter 00.01 it will show 19.97 and if i delete that .01 to 0 it will remain 19.97

TextWatcher shouldn't be used this way, it is designed as a watcher not an interactor.
I think you try to do something when edit is done. You should use FocusListener instead.
txtDiscount.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus)
// here focus is lost, means edit is done, validate text here
}

Related

Android Studio: only accept input if its a letter using TextChangedListener

I'm working on an app using Android Studio where I want to take input from the user and use it later on.
I want to only accept this input if its a letter. If the user inputs a number I want to show the user an error message instead of accepting the input.
This is the code I'm currently working on, at the moment it accepts whatever input the user enters:
EditText input;
input.setText("");
input = findViewById(R.id.input);
input.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) {
if (charSequence.length() != 0) {
useInputLaterOn(charSequence.charAt(0));
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
Use this code to check for a letter and show error if it's not a letter
input.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) {
if (charSequence.length() == 0) return;// No need to check because there's no text
Pattern pattern = Pattern.compile("^[a-zA-Z ]+$");
Matcher matcher = pattern.matcher(charSequence.toString());
if (!matcher.matches()) {
// It's not a letter
// Remove last entered character and show error message
input.setText(charSequence.toString().substring(0, charSequence.toString().length() - 1));
input.setSelection(input.getText().toString().length());
input.setError("Not a letter");
} else {
// It's a letter do something
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});

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

How to include spaces in addTextChangeListener()?

How do I include spaces in the EditText in onTextChanged()? Like SQL query SELECT * FROM Customers WHERE CustomerName LIKE '%a %';
In my code, upon typing the keyword + space it will vanish the result. for example, I want to find "King Pin" then I typed into EditText "King P" but the method doesn't generate the result.
adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, title);
listView.setAdapter(adapter);
editText.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) {
myFragment.this.adapter.getFilter().filter(charSequence);
}
#Override
public void afterTextChanged(Editable s) {
}
});
Its kind of tricky to check for spaces in addTextChangeListener. Generally people try to avoid the space issue by using trim() method and also put code in afterTextChanged(Editable s) method for better results. Try using
#Override
public void afterTextChanged(Editable s) {
myFragment.this.adapter.getFilter().filter(s.toString()).trim();
}

Enter double space to replace comma in multiautocompletetextview

I want to add comma when I enter double space from keyboard in multiautocompletetextview. I search lots of thing in google. But can't reach my goal. I want to replace comma for double space entering by user.
So obviously, I must have to write something logic in ontextChange() or OnAfterTextChanged() in addtextwatcher listener.but i do't got event of after add 2 space.
I have already used comma tokenizer when select word from list.but i want to add comma when user entering double space using keypad.
Thanks in advance
The simplest solution i can provide you is to use String.replace(), Here is small code snippet to help you
#Override
protected void onCreate(Bundle savedInstanceState) {
...
edt.addTextChangedListener(textWatcher);
}
And TextWatcher which you are going to set on EditText
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) {
edt.removeTextChangedListener(textWatcher);
String text = edt.getText().toString();
text = text.replace(" ", ",");
edt.setText(text);
edt.setSelection(text.length());
edt.addTextChangedListener(textWatcher);
}
#Override
public void afterTextChanged(Editable editable) {
}
};
Try like this, I have not tried this code
boolean userPressedKey = false ;
int spaceCount = 0;
yourEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
userPressedKey = false ;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
userPressedKey = true;
});
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (userPressedKey) {
if (keyCode == KeyEvent.KEYCODE_SPACE) {
spaceCount ++;
if(spaceCount == 2){
//append comma to the edittext here
Toast.makeText(MainActivity.this, "White space is clicked twice", Toast.LENGTH_LONG).show();
}
return true;
}else{
spaceCount=0;
}
}
super.onKeyDown(keyCode, event);
}

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