How do i set fractional part of 2 digits in my editText? - android

I am using filter to set the length of editText.
I set EditText length as 10 as per following.
TextView editVew = new TextView(R.id.txtAmt);
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(10);
editVew.setFilters(FilterArray);
editVew.setInputType(InputType.TYPE_CLASS_NUMBER);
My confusion : how to set fraction of 2 digits in my number and total length of my editview should not exceed 10 digits ?
If any body knows please reply.
Thanks

Try this to make your edittext support two digits after decimals.
EditText text = (EditText) findViewById(R.id.txtAmt);
text.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable edittext)
{
String str= edittext.toString();
int posDot = str.indexOf(".");
if (posDot <= 0) return;
if (str.length() - posDot - 1 > 2)
{
edt.delete(posDot + 3, posDot + 4);
}
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
});
And use android:maxLength="10" in xml to restrict your editText support 10 maximmum input digits

Try this..
maxLength = 10;
smsType = "free";
FilterArraySeventy[0] = new InputFilter.LengthFilter(maxLength);
message.setFilters(FilterArrayten);

Solution for your Answer
amountEditText.setRawInputType(Configuration.KEYBOARD_12KEY);
amountEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(!s.toString().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$"))
{
String userInput= ""+s.toString().replaceAll("[^\\d]", "");
StringBuilder cashAmountBuilder = new StringBuilder(userInput);
while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
cashAmountBuilder.deleteCharAt(0);
}
while (cashAmountBuilder.length() < 3) {
cashAmountBuilder.insert(0, '0');
}
cashAmountBuilder.insert(cashAmountBuilder.length()-2, '.');
cashAmountBuilder.insert(0, '$');
amountEditText.setText(cashAmountBuilder.toString());
// keeps the cursor always to the right
Selection.setSelection(amountEditText.getText(), cashAmountBuilder.toString().length());
}
}
});
Same Question discussed here
Ref Link

Related

android TextWatcher beforeTextChanged problem

in my application i have many edit text and i implemented textWatcher for them i want them to increase and decrease a textView number but i can only increase it
i tried to check if the old text is bigger that new text and decrease the textview number, but it returns false everytime
my code :
editText.addTextChangedListener(new TextWatcher() {
String oldText = "";
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
this.oldText = s.toString();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (!editText.getText().toString().equals("")) {
int price = Integer.parseInt(editText.getText().toString()) * price_db;
productPrice.setText(price + "");
int totalPrice_n = Integer.parseInt(totalPrice.getText().toString());
int min = Integer.parseInt(editText.getText().toString()) - Integer.parseInt(oldText);
if(Integer.parseInt(editText.getText().toString()) > Integer.parseInt(oldText)){
totalPrice.setText((totalPrice_n + min * price_db) + "");
}else{
totalPrice.setText((totalPrice_n - min * price_db) + "");
}
}
}
});
my problem is that if condition only returns false and goes to else part, also my EditText default text is set to 0 so i think beforeTextChanged only take on 0 and check if new text is bigger than 0
i change editText's text with 2 button ( + , - ) and i want when i click on + button to increase the TextView number and also when i click on - button to decrease TextView number but it only increase it i dont know why
Replace my code with your code and check dude !!! :)
editText.addTextChangedListener(new TextWatcher() {
String oldText = "";
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
this.oldText = s.toString();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (!editText.getText().toString().equalsIgnoreCase(""))
{
int amount=Integer.parseI`enter code here`nt(editText.getText().toString());
int price = Integer.parseInt(editText.getText().toString()) * price_db;
int totalPrice_n = Integer.parseInt(totalPrice.getText().toString());
productPrice.setText(price);
int min = amount - Integer.parseInt(oldText);
if(Integer.parseInt(oldText) > 0)
{
if(amount > Integer.parseInt(oldText)){
totalPrice.setText((totalPrice_n + min * price_db));
}else{
totalPrice.setText((totalPrice_n - min * price_db));
}
}
else
Toast.makeText(context,"old text is 0",Toast.LENGTH_LONG).show();
}
}
});

Validate input in Edittext after enter data in Android

I have layout in my application like below: When i enter 100 from soft keyboard in edit text it should show correct answer toast automatically and it should allow only 3 numbers to enter in input text.
How to do this?
10 x 10 = ___
i tried with Textwatcher but its not working. When i enter correct answer EditText 10 X 10 should change to next value.
int min = 0;
int max = 20;
Random r = new Random();
int mRandomOne = r.nextInt(max - min + 1) + min;
int mRandomTwo = r.nextInt(10 - 0 + 1) + 0;
mFillAnswer = (EditText) findViewById(R.id.fill);
mFillAnswer.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) {
int a = Integer.parseInt(mOneValue.getText().toString());
int b = Integer.parseInt(mTwoValue.getText().toString());
int val = Integer.parseInt(mFillAnswer.getText().toString());
if (val == (a * b)) {
mOneValue.setText(String.valueOf(mRandomOne));
mTwoValue.setText(String.valueOf(mRandomTwo));
}
}
#Override
public void afterTextChanged(Editable s) {
mOneValue.setText(String.valueOf(mRandomOne));
mTwoValue.setText(String.valueOf(mRandomTwo));
}
});
For allowing only 3 numbers use android:maxLength="3" in your EditText
For automatically detecting the correct or incorrect answer use TextWatcher
Update
To change the TextView values:
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//To avoid exception
if(mFillerAnswer.getText().toString().equals("")){return;}
int a = Integer.parseInt(mOneValue.getText().toString());
int b = Integer.parseInt(mTwoValue.getText().toString());
int val = Integer.parseInt(mFillAnswer.getText().toString());
if (val == (a * b)) {
//generate and use Random numbers here
mOneValue.setText(r.nextInt(max - min + 1) + min);
mTwoValue.setText(r.nextInt(10 - 0 + 1) + 0);
//to clear edit text
mFillAnswer.setText("")
}
}
You were generating random numbers only once so it was pointless to be expecting newer values while the generation code is outside the TextWatcher scope

Want to format the number in EditText

I want to format the input which is in the form of number in EditText.The format is 01-133134-124. I wanted first - after 2 number then next dash after 6 numbers.I tried but whenever I pressed delete/backspace because of the wrong entry the format stopped working and no dash is placed after input of 2 number or 6 numbers.Here is the code.Where Enrollement is the EditText field.
Format : 2digitnumber-6dignumber-3dignumber
Enrollement.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Enrollement.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL)
keyDel = 1;
return false;
}
});
if (keyDel == 0) {
int len = Enrollement.getText().length();
if (len == 2) {
int leng = Enrollement.getText().length();
if(leng==2) {
Enrollement.setText(Enrollement.getText() + "-");
Enrollement.setSelection(Enrollement.getText().length());
}
} else if (len == 9) {
int leng = Enrollement.getText().length();
if(leng==9) {
Enrollement.setText(Enrollement.getText() + "-");
Enrollement.setSelection(Enrollement.getText().length());
}
}
} else {
keyDel = 0;
}
}
#Override
public void afterTextChanged(Editable arg0) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
});
It would be much easier if you changed your approach a bit. You could be always analyzing unformatted verion of your string after every single change in your EditText.
Try this (remember to set android:maxLength="13" for your EditText):
Enrollement.addTextChangedListener(new TextWatcher() {
final int[] blockLengths = new int[]{2, 6, 3};
String mUnformatted = "";
#Override
public void onTextChanged (CharSequence s,int start, int before, int count){
String unformattedSeq = s.toString().replace("-", "");
if (mUnformatted.length() == unformattedSeq.length()) {
return; //length of text has not changed
}
mUnformatted = unformattedSeq;
//formatting sequence
StringBuilder formatted = new StringBuilder();
int blockIndex = 0;
int currentBlock = 0;
for (int i = 0; i < mUnformatted.length(); ++i) {
if (currentBlock == blockLengths[blockIndex]) {
formatted.append("-");
currentBlock = 0;
blockIndex++;
}
formatted.append(mUnformatted.charAt(i));
currentBlock++;
}
Enrollement.setText(formatted.toString());
Enrollement.setSelection(formatted.length());
}
#Override
public void beforeTextChanged (CharSequence s,int start, int count, int after){
}
#Override
public void afterTextChanged (Editable s){
}
});
This code should work correctly. You could only improve the setSelection part (currently if you delete a number in the middle of your EditText it will move your cursor to the end of the text).
In your onTextChanged method you could do:
String str = YourEditText.getText().toString();
if((str.length()==2 && len <str.length()) || (str.length()==6 && len <str.length())){
YourEditText.append("-"); }
Also,
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
String str = YourEditText.getText().toString();
len = str.length();
}
Adapted from this article.

Android EditText with decimal value in format (3,2)

I have search a lot but not found solution to my problem.
How can I have a editText in which user can enter number in decimal format in which format should be a integer before decimal and two integer after decimal.
If user enter 1 then it should be 1.00 and not allow to enter value grater then 9.99.
I have refer different code but nothing is working.
below is my code -
public class DecimalDigitsInputFilter implements InputFilter {
Pattern mPattern;
public DecimalDigitsInputFilter(int digitsBeforeZero,int digitsAfterZero) {
mPattern=Pattern.compile("[0-9]{0," + (digitsBeforeZero-1) + "}+((\\.[0-9]{0," + (digitsAfterZero-1) + "})?)||(\\.)?");
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
Matcher matcher=mPattern.matcher(dest);
if(!matcher.matches())
return "";
return null;
}
}
and
mSetupProfileViewHolder.mAthleteGPAET.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(3,2)});
but it allow user to input value all inter like 333,999 etc.
You want to use a TextWatcher and then check what the user has typed before they submit it. Here is an example of the code you want to implement:
final EditText et = (EditText) findViewById(R.id.editText);
et.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {
}
public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {
}
public void afterTextChanged(Editable arg0) {
if (arg0.length() > 0) {
String str = et.getText().toString();
et.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL) {
count--;
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(100);
et.setFilters(fArray);
//change the edittext's maximum length to 100.
//If we didn't change this the edittext's maximum length will
//be number of digits we previously entered.
}
return false;
}
});
char t = str.charAt(arg0.length() - 1);
if (t == '.') {
count = 0;
}
if (count >= 0) {
if (count == 2) {
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(arg0.length());
et.setFilters(fArray);
//prevent the edittext from accessing digits
//by setting maximum length as total number of digits we typed till now.
}
count++;
}
}
}
});
The above code will not allow the user to enter more than two digits after the decimal point and you can also enter any number of digits before the decimal point. Hope this helps, let me know if you have any issues!

Allow only two decimal input EditText

I need the EditText allow only seven integer and two decimal numbers. Ex: 7777777.99
I try with this Regex, in onTouchListener event, but not working. By the way, this is the correct event to do this??
txtRespNumero.addTextChangedListener(new TextWatcher() {
int count = 0; // Declare as Instance Variable
boolean isSeven = true; // Declare as Instance Variable
public void onTextChanged(CharSequence s, int start, int before,
int count) {
count++;
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
if(isSeven){
if(count == 7){
s.append(".");
isSeven = true;
}
}
if(count < 7){
isSeven = true;
}
}
});
Try it this way...
- Set the EditText Attribute Max Length as 10.
- Then when you accept the EditeText value, convert it into format of 0000000.00 using the below example:
Eg:
double d = 300.0;
DecimalFormat df = new DecimalFormat("0000000.00");
System.out.println(df.format(d));
/////////////////////////////////// Edited Part /////////////////////////////
Another way to do it, just as you want it.........
int count = 0; // Declare as Instance Variable
boolean isSix = true; // Declare as Instance Variable
tx = (EditText) findViewById(R.id.editText_CheckIt);
tx.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
count++;
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
if(isSeven){
if(count == 7){
s.append(".");
isSeven = true;
}
}
if(count < 7){
isSeven = true;
}
}
});
Try the onTextChanged rather, it get called everytime the user enters a numer (In your case) instead of only once when the control is touched). This solution worked for me:
EditText no more than x decimals android
It is a pity that android does not allow you do this directly in the XML though.

Categories

Resources