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?
Related
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, "", "");
}
This is my activity
String name =et.getText().toString();
String a = "a";
String a1 = "\u24B6";
String b = "b";
String b1 = "\u24B7";
String c = "c";
String c1 = "\u24B7";
String d = "d";
String d1 = "\u24B9";
String e = "d";
String e1 = "\u24BB";
name = name.replaceAll(a,a1);
name = name.replaceAll(b,b1);
name = name.replaceAll(c,c1);
name = name.replaceAll(d,d1);
name = name.replaceAll(e,e1);
tv.setText(name);
when write a or b or c in edittext show space in textview
what is solution?
Use a TextWatcher on your EditText.
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);
// make changes to s here
et.addTextChangedListener(this);
}
});
The app force shuts when i enter a number in edittext. I want the app to automatically calculate the BMI when values are entered without pressing on a button.
I know nothing about TextWatcher yet i researched and came up with this code. Its not working though. Whats wrong with it?
public class BodyMassIndex extends Activity implements View.OnClickListener,
TextWatcher {
double result;
EditText age, height, weight;
ToggleButton sex, cmin, kglb;
TextView tvResult;
double heightInt = 1;
double weightInt = 0;
int ageInt;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.bmi);
initialize();
sex.setOnClickListener(this);
cmin.setOnClickListener(this);
kglb.setOnClickListener(this);
}
private void initialize() {
// TODO Auto-generated method stub
age = (EditText) findViewById(R.id.etAge);
height = (EditText) findViewById(R.id.etHeight);
weight = (EditText) findViewById(R.id.etWeight);
sex = (ToggleButton) findViewById(R.id.tbSex);
cmin = (ToggleButton) findViewById(R.id.tbCMIN);
kglb = (ToggleButton) findViewById(R.id.tbKGLB);
tvResult = (TextView) findViewById(R.id.tvResult);
age.addTextChangedListener(this);
height.addTextChangedListener(this);
weight.addTextChangedListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.tbCMIN:
heightInt = heightInt * 0.0254;
break;
case R.id.tbKGLB:
weightInt = weightInt * 0.45359237;
break;
}
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
calculate();
}
private void calculate() {
// TODO Auto-generated method stub
Editable H = height.getText(), W = weight.getText();
if(H != null)
heightInt = Double.parseDouble(H.toString());
if (W != null)
weightInt = Double.parseDouble(W.toString());
result = weightInt / (heightInt * heightInt);
String textResult = "Your BMI is " + result;
tvResult.setText(textResult);
}
#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) {
// TODO Auto-generated method stub
}
}
'
From http://developer.android.com/reference/android/text/TextWatcher.html about afterTextChanged method: "but be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively....you can use setSpan(Object, int, int, int) in onTextChanged(CharSequence, int, int, int) "
you already have :
height = (EditText) findViewById(R.id.etHeight);
weight = (EditText) findViewById(R.id.etWeight);
only change calculate() method:
private void calculate()
{
//remove the Editable thing declaration...
heightInt = Double.parseDouble(height.getText().toString());
wightInt = Double.parseDouble(weight.getText().toString());
result = weightInt / (heightInt * heightInt);
String textResult = "Your BMI is " + result;
tvResult.setText(textResult);
}
P.S: Here we're assuming that EditText contains only a number and not letters. Letters will force close the app. So you'll have to check for that.
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?
i have a problem with handler in android, i don't understand not display result, this's code:
public class Main extends Activity implements OnClickListener {
private EditText nhap;
private Button btTinh;
private Button btHuy;
private TextView kq;
private ProgressDialog progress;
private Handler handle = new Handler();
private int count = 0;
private String s = "";
private long n;
handlemessage:
Handler mhandle = new Handler() {
#Override
public void handleMessage(Message msg) {
kq.setText(msg.obj.toString());
}
};
onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nhap = (EditText) findViewById(R.id.nhap);
btTinh = (Button) findViewById(R.id.btTinh);
btHuy = (Button) findViewById(R.id.btHuy);
kq = (TextView) findViewById(R.id.kq);
btTinh.setOnClickListener(this);
btHuy.setOnClickListener(this);
}
public boolean checkPrime(long n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0)
return false;
}
return true;
}
outprime:
public void outPrime(long t) {
// String s="";
progress.setCancelable(true);
progress.setMessage("File downloading ...");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setProgress(0);
progress.setMax(Integer.parseInt(nhap.getText().toString()));
progress.show();
n = t;
new Thread() {
public void run() {
for (int i = 2; i < n; i++) {
count = i;
if (checkPrime(i))
s = s + i + " ";
handle.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
progress.setProgress(count);
}
});
}
if (count == n - 1) {
progress.dismiss();
Message msg = handle.obtainMessage(1, (String)s);
handle.sendMessage(msg);
}
}
}.start();
}
onclick:
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btTinh:
progress = new ProgressDialog(this);
outPrime(Long.parseLong(nhap.getText().toString()));
break;
case R.id.btHuy:
nhap.setText("");
break;
}
}}
this's handlemessage:
Handler mhandle = new Handler() {
#Override
public void handleMessage(Message msg) {
kq.setText(msg.obj.toString());
}
};
i don't understand handlemessage don't return value, "kq.setText(msg.obj.toString());" don't display to screen, sorry because my english not good
I think the answer for your question is "Watch out your variable's names!" Look - you've created 2 Handlers - named "mhandle" and "handle". You want to parse message in Handler named "mhandle", but in your Thread send it to "handle", which is doing nothing from your code.
Hope it will help if you still trying to find the answer.