In my application, I want to get a phone number from the user and if the first 2 characters of this number are 09, I want to show Toast.
I wrote the code below, but it always shows me the Toast message.
My code:
phoneNumberPage_phoneEdtTxt.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().length() < 11) {
enableDisableBtn(0.3f, false);
} else {
hideKeyboard(activity);
enableDisableBtn(1.0f, true);
}
}
#Override
public void afterTextChanged(Editable s) {
if (s.toString().trim().length()==1){
if (!s.equals("0")){
Toast.makeText(context, "NOOOOOO", Toast.LENGTH_SHORT).show();
}
}
}
});
}
How can I do it? Can you please help me?
using startsWith
if(s.startsWith("09")){
or you can use matches with regex
if(s.matches("09(.*)"))
You should check String reference especially substring method. In your case you can use substring like this:
String twoFirstCharacters = string.substring(0, 2);
if (twoFirstCharacters.equals("09")) {
// here we go
}
Use String.startsWith() method
#Override
public void afterTextChanged(Editable s) {
if (s!=null&& !s.toString().trim().isEmpty()){ // make sure String value is there
if (!s.startsWith("09")){ // check string qualifies your requirement
Toast.makeText(context, "NOOOOOO", Toast.LENGTH_SHORT).show();
}
}
}
Related
I am trying to implement something similar to a code editor where keywords are automatically highlighted. I am going to have a string array and I want to change the color and font of the editText string when the user types the text and it matches a string from the string array. I am using the addTextChangeListener but the text of the whole editText changes. I want just the matched word to be highlighted. Here is my code:
inputCodeEditText.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().contains("for"))
{
inputCodeEditText.setTextColor(getResources().getColor(R.color.indigo));
}
}
});
I understand I have to use spans but the code crashes. Can anyone help me with the correct usage of spannable strings with addTextChangedListener() ?
Use addTextChangeListener API eg:
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) {
// The changed text comes in "s" parameter.
// Here you can watch the changes and take an action you want...
}
#Override
public void afterTextChanged(Editable s) {
}
});
I have 2 buttons and 1 number field, if I press a button without something in the field, it crashes, so what I want to do is disable the buttons unless the number field has something in it, I have looked around for an answer but either they aren't relevant, or I'm not sure how it would fit into my code, here are the two onClick functions for each button. Thanks
public void toPounds(View view){
EditText amount = (EditText)findViewById(R.id.amount);
Double omrAmount = Double.parseDouble(amount.getText().toString());
Double gbrAmount = omrAmount * 1.79;
Toast.makeText(getApplicationContext(), "£" + gbrAmount.toString(), Toast.LENGTH_LONG).show();
}
public void toRiyals(View view){
EditText amount = (EditText)findViewById(R.id.amount);
Double gbrAmount = Double.parseDouble(amount.getText().toString());
Double omrAmount = gbrAmount / 1.79;
Toast.makeText(getApplicationContext(), omrAmount.toString() + " Riyals", Toast.LENGTH_LONG).show();
}
yourField.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {}
#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() == 0)
button1.setEnabled(false)
else
button1.setEnabled(true)
}
});
link
If you want to disable buttons if edit text is empty then you can do the following :
EditText amount = (EditText)findViewById(R.id.amount);
Button button = (Button) findViewById(R.id.button1);
if(amount.getText().toString().isEmpty()){
button.setEnabled(false);
}
amount.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {}
#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() == 0)
button1.setEnabled(false)
else
button1.setEnabled(true)
}
});
Not specifically an answer to your question, but generally speaking you would want to add some sort of check before you call your code which now crashes your application. It's not a good idea to to have code which crashes your app lingering around.
Maybe make a method like: isMyEditTextValid(...){..}
The code below produce an stackoverflow error. The idea is to format the amount when or after user type an amount.
500 -> 500.00
1000 -> 1 000.00
29999.55-> 29 999.55
..
..
..
edit_amount.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
if (edit_amount.getText().toString().length()>0){
edit_amount.setText(
currencyFormat(edit_amount.getText().toString()));
}else {}
}
});
public String currencyFormat(String number){
String credits="";
try {
//en, us
if (TextUtils.isEmpty(MyApplication.pref.GetPreferences("AppCurrency"))){
credits = NumberFormat.getCurrencyInstance(new Locale("fr", "FR")).format(Double.valueOf(number));
}else {
if (MyApplication.pref.GetPreferences("AppCurrency").equals("Euro")) {
credits = NumberFormat.getCurrencyInstance(new Locale("fr", "FR")).format(Double.valueOf(number));
} else {
credits = NumberFormat.getCurrencyInstance(new Locale("en", "US")).format(Double.valueOf(number));
}
}
}catch(Exception ex){
credits = "mCredits";
}
return credits;
}
Your code doesn't work because when you call edit_amount.setText(...) then the afterTextChanged(Editable s) is triggered and then edit_amount.setText(...) is triggered and so on. You need to change your logic to do what you want and avoid stack overflow.
For example you could unregister TextWatcher, setText and then register it again.
Alternatively, you can set a flag so that your TextWatcher knows when you change the text yourself and then instruct TextWatcher to ignore it.
To avoid recursive invocation of afterTextChanged callback you can set up additional chek. Smth like this
#Override
public void afterTextChanged(Editable s) {
if (et.getText().toString().length() > 0) {
String src = et.getText().toString();
String origin = currencyFormat(src);
if(!src.equals(origin)) {
et.setText(currencyFormat(et.getText().toString()));
}
}
}
Try below code :
private String current = "";
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(!s.toString().equals(current)){
[your_edittext].removeTextChangedListener(this);
String cleanString = s.toString().replaceAll("[$,.]", "");
double parsed = Double.parseDouble(cleanString);
String formatted = NumberFormat.getCurrencyInstance().format((parsed/100));
current = formatted;
[your_edittext].setText(formatted);
[your_edittext].setSelection(formatted.length());
[your_edittext].addTextChangedListener(this);
}
}
I have a number of EditText's with an inputType="numberDecimal" and i'm wanting to change the input into currency (TextWatcher maybe?). Can anyone help with this? 99% of my project is done bar this. Thanks guys.
try below code:-
tv.addTextChangedListener(new TextWatcher()
{
private String current = "";
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if(!s.toString().equals(current))
{
if(tv.getText().toString().trim().length()>0)
{
tv.removeTextChangedListener(this);
String formated = tv.getText().toString().trim().replace("$", "");
current = formated;
tv.setText("$"+formated);
tv.setSelection(formated.length()+1);
tv.addTextChangedListener(this);
}
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void afterTextChanged(final Editable s)
{
}
});
i use a TextWatcher to change pressed key value. my goal is that replace some characters while typing. for example when i type keys, if reached "S" character, replaces it with "a" character. my question is: should i do it in beforeTextChanged?? how? can anyone give me an example?
I know that this post is a couple of years old, but both versions did not work for me and have build a hybrid between the two answers.
#Override
public void afterTextChanged(Editable editable) {
if (editable.toString().contains(",")) {
Editable ab = new SpannableStringBuilder(editable.toString().replace(",", ""));
editable.replace(0, editable.length(), ab);
}
}
Using beforeTextChanged won't be useful because it won't interrupt the actual printing of the key to the EditText. I would use something similar to:
public void afterTextChanged(Editable s) {
if(s.length() > 0 && s.toString().charAt(s.length()-1) == 'S')
{
final String newText = s.toString().substring(0, s.length()-1) + "a";
editText.setText(newText);
}
}
I added some toString()'s, not 100% sure how Editable works but I think that should cover it.
You have to do it in the afterTextChanged, but don't forget to detach
and reattach the TextChangedListener to prevent an endless loop.A simple example is shown below :
public void afterTextChanged(Editable s) {
editText.removeTextChangedListener(this);
//.. do changes here ..//
editText.setText(newText);
editText.addTextChangedListener(this);
}
But there is another problem when you call setText, it causes the cursor to move to the end of the text inside the textView. So you have to calculate the new position for the curser yourself, remember user may enter the multiple characters at once by pasting or delete a selected part of the text.Here is a more complete example. This watcher class removes all nonnumeric characters of the text.
public class NumWatcher implements TextWatcher {
private EditText editText;
private int selPos;
private String oldString, newString;
public NumWatcher(EditText editText) {
this.editText = editText;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
selPos = editText.getSelectionStart();
oldString = myFilter(s.toString());
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
editText.removeTextChangedListener(this);
newString = myFilter(s.toString());
editText.setText(newString);
int newPos = selPos + (newString.length() - oldString.length());
if (newPos < 0) newPos = 0;
editText.setSelection(newPos);
editText.addTextChangedListener(this);
}
public String myFilter(String s) {
String digits;
digits = s.replaceAll("[^0-9]", "");
if (s.equals("")) return "";
return digits;
}
}
#Override
public void afterTextChanged(Editable arg0) {
Editable ab = new SpannableStringBuilder(arg0.toString().replace("S", "a"));
arg0 = ab ;
}