How to add number separators in EditText - java

I have an Edittext and want to set the EditText so that when the user is inputting the number to be converted, a thousand separator (,) should be added automaticaaly in realtime to the number .but i want do this in "onTextChanged" method not in the "afterTextChanged" method. How can I?
public class NumberTextWatcherForThousand implements TextWatcher {
EditText editText;
public NumberTextWatcherForThousand(EditText editText) {
this.editText = editText;
}
#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 view) {
String s = null;
try {
// The comma in the format specifier does the trick
s = String.format("%,d", Long.parseLong(view.toString()));
edittext.settext(s);
} catch (NumberFormatException e) {
}
}

Try this code:
et.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
try {
String givenstring = s.toString();
Long longval;
if (givenstring.contains(",")) {
givenstring = givenstring.replaceAll(",", "");
}
longval = Long.parseLong(givenstring);
DecimalFormat formatter = new DecimalFormat("#,###,###");
String formattedString = formatter.format(longval);
et.setText(formattedString);
et.setSelection(et.getText().length());
// to place the cursor at the end of text
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
et.addTextChangedListener(this);
}
});

I use a TextWatcher to trig on every change in EditText, and use this code to separate currency sections and then set to EditText after every character changes:
public static String formatCurrencyDigit(long amount) {
return String.format("%,d%s %s", amount, "", "");
}

Related

How to get the last word typed in a `EditText`?

I am building a proto social network and I give the possibility to my users to Tag another user with the # , I'm using an autocomplete textview to show the dialog with the users # searched but I need to know when a user typed "#" and the letters following in the editext . I found this answer and it's exaclty what I need BUT I dont want to only get one character. I want the whole word to make a search in my database . Example, user types "#Jordan" in the middle of his paste text . I need to get the "#" and the "#Jordan " . How can I do it ?
Here s an example of my code
private final 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) {
if (!TextUtils.isEmpty(s) && start < s.length()) {
if (!mentionAdapter.isEmpty()) {
mentionAdapter.clear();
}
String lastWord = s.toString().substring(s.toString().lastIndexOf(" ") + 1);
if (lastWord != null){
if (lastWord.length() != 0) {
switch (lastWord.charAt(0)) {
case '#':
if (getAdapter() != hashtagAdapter) {
setAdapter(hashtagAdapter);
}
break;
case '#':
if (getAdapter() != mentionAdapter) {
setAdapter(mentionAdapter);
}
break;
}
}
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
I am aiming you are working on android java so here is the answer to your question
EditText editText = (EditText)findViewById(R.id.editText);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
String capturedString = getText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
});
this function will work whenever you tab spacebar "#Jordan " you will get string after '#' and before ' ' means you will get "Jordan" as a string
public String getText(String s) {
String startChar = "#";
String endChar = " ";
String output = getStringBetweenTwoChars(s, startChar, endChar);
System.out.println(output);
}
here is getStringBetweenTwoChars function
public String getStringBetweenTwoChars(String input, String startChar, String endChar) {
try {
int start = input.indexOf(startChar);
if (start != -1) {
int end = input.indexOf(endChar, start + startChar.length());
if (end != -1) {
return input.substring(start + startChar.length(), end);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return input;
}
You can do that by following code, If you want to #java from the string
**Hello this is #java the best programming language **
edt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(final CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable editable) {
String str = editable.toString();
String seperator = "#";
int seoPos = str.indexOf(seperator);
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(str);
boolean found = matcher.find();
if (seoPos != -1 && !found){
Log.d("TextChanged0","current Char "+str.substring(seoPos-1+seperator.length()));
}
}
});
String last = s.toString().substring(s.toString().lastIndexOf(" ") + 1);

Filter Edittext to accept word or number that doesn't start with 0

what I'm trying to do is to make Editext except only word or number that not start with zero so I did this
mPatentNameET.setFilters(new InputFilter[] {
new InputFilter() {
public CharSequence filter(CharSequence src, int start,
int end, Spanned dst, int dstart, int dend) {
if(src.equals("")){ // for backspace
return src;
}
if(src.toString().matches("[a-zA-Z ]+") ||
src.toString().matches("^[123456789][0-9]$")){
return src;
}
return "";
}
}
});
but didn't work well, I want from EditText to accept for example "Test" or "546" , sorry for my bad English
I solve it like this :)
mPatentNameET.setFilters(new InputFilter[] {
new InputFilter() {
public CharSequence filter(CharSequence src, int start,
int end, Spanned dst, int dstart, int dend) {
if(src.equals("")){ // for backspace
return src;
}
if((mPatentNameET.getText().toString() + src).matches("[a-zA-Z ]+") ||
(mPatentNameET.getText().toString() + src).matches("^[123456789][0-9]*$")){
return src;
}
return "";
}
}
});
you could use a TextWatcher. something like this:
mPatentNameET.addTextChangedListener(new TextWatcher(){
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
String EditTextString= tx.getText().toString();
if(EditTextString.charAt(0).equals("0")){
//TODO return when starting with 0
}
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});

Values of EditText fields are changed depends on each other

I'm trying to build temperature converter (F -> C and C -> F).
I have 2 ET fields. when user types in one, the other displays converted value and vice verse.
I understand that similar programs has been build already, but I couldn't find solution.
It works fine for one field, but app closes when I try to edit the other one.
Here is my piece of code:
public class Temp extends Activity implements OnClickListener, OnFocusChangeListener {
private EditText temp_f, temp_c;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.temp);
temp_f = (EditText) findViewById(R.id.temp_f_inp);
temp_c = (EditText) findViewById(R.id.temp_c_inp);
temp_c.setOnFocusChangeListener((OnFocusChangeListener) this);
temp_f.setOnFocusChangeListener((OnFocusChangeListener) this);
}
private TextWatcher tempc = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (temp_c.getText().length() == 0)
{
temp_f.setText("");
} else {
float convValue = Float.parseFloat(temp_c.getText()
.toString());
conv_f = ((convValue - 32) * 5 / 9);
temp_f.setText(String.valueOf(new DecimalFormat(
"##.###").format(conv_f)));
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void afterTextChanged(Editable s) {
}
};
private TextWatcher tempf = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start,int before, int count) {
// TODO Auto-generated method stub
if (temp_f.getText().length() == 0)
{
temp_c.setText("");
} else {
float convValue = Float.parseFloat(temp_f.getText()
.toString());
conv_c = ((convValue * 9) / 5 + 32);
temp_c.setText(String.valueOf(new DecimalFormat(
"##.###").format(conv_c)));
}
#Override
public void beforeTextChanged(CharSequence s, int start,int count, int after) {}
#Override
public void afterTextChanged(Editable s) {
}
};
#Override
public void onFocusChange(View v, boolean hasFocus) {
if ((v == findViewById(R.id.temp_c_inp)) && (hasFocus==true)) {
temp_c.addTextChangedListener(tempc);
}
else if((v == findViewById(R.id.temp_f_inp)) && (hasFocus==true)){
temp_f.addTextChangedListener(tempf);
}
}
it seems like onTextChanged still holds the values of the first ET that has been modified and when I try to edit the other ET fields, it throws an error.
Any help would be greatly appreciated!
Thank you!
You could try this:
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (v.equals(findViewById(R.id.temp_c_inp))) {
if(hasFocus){
temp_c.addTextChangedListener(tempc);
}else{
temp_c.removeTextChangedListener(tempc);
}
}
else if(v.equals(findViewById(R.id.temp_f_inp))){
if(hasFocus){
I temp_f.addTextChangedListener(tempf);
}else{
temp_f.removeTextChangedListener(tempf);
}
}
}
I haven't tried the code by myself, but I hope it could help you
Logic seems to be a problem.
What I would do is,
1. On text change, do nothing (or just check for valid input values)
2. On focus change, do conversion and populate other text field.
Also, you have some #Override functions which are essentially null functions. Why override?

To grab text from Edit text and highlight this text in Current text view

I working on module to search grab text from edit text and search it into current text view. If present highlight this text in current text view. I also googled for this code but didn't found any relevant answer.
tv=(TextView) mView.findViewById(R.id.detailsText);
edit_text=(EditText)findViewById(R.id.searchText);
edit_text.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) {
hightLightText(tv, s.toString());
}
});
}
void hightLightText(TextView textView, String searchString){
try{
String s=getResources().getString(R.string.firstpage);
String withHighLightedText = s.replaceAll(searchString, "<font color='red'>"+searchString+"</font>");
String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(withHighLightedText), TextView.BufferType.SPANNABLE);
}catch(Exception ex){
}
}
HTML tag formatting within TextView is very limited.
<b>Bold</b> and <i>Italic</i>
do work, but
<font color>
sadly does not.
Use Spannable instead to highlight to portions of text you want.
Here is an example for making selected text Italic within an EditText View: Is there any example about Spanned and Spannable text
call the below function for highlighting.
public void hightLightText(TextView textView, String searchString) {
String s = textView.getText().toString();
SpannableString str = new SpannableString(s);
if (searchString != null && !searchString.equalsIgnoreCase("")) {
int startIndex = 0;
while (true) {
startIndex = s.indexOf(searchString, startIndex);
if (startIndex >= 0) {
str.setSpan(new BackgroundColorSpan(Color.YELLOW),
startIndex, startIndex + searchString.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
startIndex++;
} else {
break;
}
}
}
textView.setText(str);
}
EditText edit_text;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edittest);
tv=(TextView) findViewById(R.id.detailsText);
edit_text=(EditText)findViewById(R.id.searchText);
edit_text.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) {
hightLightText(tv, edit_text.getText().toString().trim());
}
});
}
void hightLightText(TextView textView, String searchString){
try{
String s=getResources().getString(R.string.app_name);
String withHighLightedText = s.replaceAll(searchString, "<font color='red'>"+searchString+"</font>");
String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(withHighLightedText), TextView.BufferType.SPANNABLE);
}catch(Exception ex){
}
}
In your code just change the bellow method
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
hightLightText(tv, edit_text.getText().toString().trim());
}

On Edittext Automatic calculation

Currently I am using my onEditTextchanger. To format my currency. What I am wondering if it is possible to call and run the Calculate function from my main java whenever the user types in the edittext field .
I would like it to work similar the the javascript function onkeyup="calc(this.form)"
Since I am not sure how to implement this. Any ideas would be appreciated. Once Again Thanks in advance for your help.
class
public class CurrencyTextWatcher implements TextWatcher {
boolean mEditing;
public CurrencyTextWatcher() {
mEditing = false;
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if(!mEditing) {
mEditing = true;
String digits = s.toString().replaceAll("\\D", "");
NumberFormat nf = NumberFormat.getCurrencyInstance();
try{
String formatted = nf.format(Double.parseDouble(digits)/100);
s.replace(0, s.length(), formatted);
} catch (NumberFormatException nfe) {
s.clear();
}
mEditing = false;
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
}
Java
public class CalcTestActivity extends Activity {
private EditText txta;
private EditText txtb;
private TextView txtc;
private TextView txtd;
private double a = 0;
private double b = 0;
private double c = 0;
private double d = 0;
private Button buttonCalc;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
txta.addTextChangedListener(new CurrencyTextWatcher());
txtb.addTextChangedListener(new CurrencyTextWatcher());
}
private void initControls() {
txta = (EditText)findViewById(R.id.txta);
txtb = (EditText)findViewById(R.id.txtb);
txtc = (TextView)findViewById(R.id.txtc);
txtd = (TextView)findViewById(R.id.txtd);
buttonCalc = (Button)findViewById(R.id.buttonCalc);
buttonCalc.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {calculate(); }});}
private void calculate() {
//textViewResult.setText(addNumbers());
a=Double.parseDouble(txta.getText().toString().replace("$", "").replace(",", ""));
b=Double.parseDouble(txtb.getText().toString().replace("$", "").replace(",", ""));
c=Math.round(a*.88);
txtc.setText(GlobalMoney.FormatValue(c));
d=Math.round((a*.87)+(b*.61)*(c*.25));
txtd.setText(GlobalMoney.FormatValue(d));
}
}
You can call it right in afterTextChanged(), is there any problem you bump into when doing so?

Categories

Resources