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
Related
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();
}
}
});
Am creating an application in which edittext adds style span to certain positions of text
editable.setSpan(new StyleSpan(Typeface.BOLD), start, start+replacement.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
My issue is that if user adds, some text or white space before the spanned text style will removed, how to avoid that ?
int SPAN_COMPOSING = 256;
int SPAN_EXCLUSIVE_EXCLUSIVE = 33;
int SPAN_EXCLUSIVE_INCLUSIVE = 34;
int SPAN_INCLUSIVE_EXCLUSIVE = 17;
int SPAN_INCLUSIVE_INCLUSIVE = 18;
int SPAN_INTERMEDIATE = 512;
int SPAN_MARK_MARK = 17;
int SPAN_MARK_POINT = 18;
int SPAN_PARAGRAPH = 51;
int SPAN_POINT_MARK = 33;
int SPAN_POINT_MARK_MASK = 51;
int SPAN_POINT_POINT = 34;
int SPAN_PRIORITY = 16711680;
int SPAN_PRIORITY_SHIFT = 16;
int SPAN_USER = -16777216;
int SPAN_USER_SHIFT = 24;
Which type will i need to use in my case ?
You can use like below code.
editable.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) {
// here is your code to change position
}
#Override
public void afterTextChanged(Editable s) {
}
});
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.
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
Is it possible to auto insert characters into an EditText as the user inputs data?
I.e. if the user is entering a long number such as 123456789012, is it possible for this number to appear as he is typing it in the edit text box, but with a dash every 4th character?
So as you type the number above you would see it being entered in the EditText box but would look like this: 1234-5678-9012.
Currently I have an app where you can enter a long number and then press a button and it inserts the dashes for you, but I'm curious if it could be done as you type?
Many thanks for any help.
By tagging android, I think you are discussing about android editText, is so you can do it by listening the TextChangedListener,
EDITED: for backspace
editText.addTextChangedListener(new TextWatcher() {
int len=0;
#Override
public void afterTextChanged(Editable s) {
String str = editText.getText().toString();
if(str.length()==4&& len <str.length()){//len check for backspace
editText.append("-");
}
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
String str = editText.getText().toString();
len = str.length();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
to solve this issue, i write a class "AutoAddTextWatcher" :
1. Auto insert text into EditText.
2. insert text into EditText at positions you are setted.
3. delete text in EditText at positions you are setted, when text length bigger than 1.
code snippet :
mEditText_birthday.addTextChangedListener(new AutoAddTextWatcher(mEditText_birthday,
"/",
new TextWatcher() {},
4, 6));
AutoAddTextWatcher class
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
/**
* Created by henry.chuang on 2016/5/12.
*/
public class AutoAddTextWatcher implements TextWatcher {
private CharSequence mBeforeTextChanged;
private TextWatcher mTextWatcher;
private int[] mArray_pos;
private EditText mEditText;
private String mAppentText;
public AutoAddTextWatcher(EditText editText, String appendText, int... position){
this.mEditText = editText;
this.mAppentText = appendText;
this.mArray_pos = position.clone();
}
public AutoAddTextWatcher(EditText editText, String appendText, TextWatcher textWatcher, int... position){
this(editText, appendText, position);
this.mTextWatcher = textWatcher;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
mBeforeTextChanged = s.toString();
if(mTextWatcher != null)
mTextWatcher.beforeTextChanged(s, start, count, after);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
for (int i = 0; i < mArray_pos.length; i++) {
if(((mBeforeTextChanged.length() - mAppentText.length() * i) == (mArray_pos[i] - 1) &&
(s.length() - mAppentText.length() * i) == mArray_pos[i])){
mEditText.append(mAppentText);
break;
}
if(((mBeforeTextChanged.length() - mAppentText.length() * i) == mArray_pos[i] &&
(s.length() - mAppentText.length() * i) == (mArray_pos[i] + 1))){
int idx_start = mArray_pos[i] + mAppentText.length() * i;
int idx_end = Math.min(idx_start + mAppentText.length(), s.length());
String sub = mEditText.getText().toString().substring(idx_start, idx_end);
if(!sub.equals(mAppentText)){
mEditText.getText().insert(s.length() - 1, mAppentText);
}
break;
}
if(mAppentText.length() > 1 &&
(mBeforeTextChanged.length() - mAppentText.length() * i) == (mArray_pos[i] + mAppentText.length()) &&
(s.length() - mAppentText.length() * i) == (mArray_pos[i] + mAppentText.length() - 1)){
int idx_start = mArray_pos[i] + mAppentText.length() * i;
int idx_end = Math.min(idx_start + mAppentText.length(), s.length());
mEditText.getText().delete(idx_start, idx_end);
break;
}
}
if(mTextWatcher != null)
mTextWatcher.onTextChanged(s, start, before, count);
}
#Override
public void afterTextChanged(Editable s) {
if(mTextWatcher != null)
mTextWatcher.afterTextChanged(s);
}
}
complete demo source :
https://github.com/henrychuangtw/AutoInsertEditText
#Override
public void afterTextChanged(Editable s) {
if(s.length() == 3 && len < s.length()){
s.append(" - ");
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
len = s.length();
}
This will do as well, only this code will insert " - " after 3rd character.
This is what I used
private boolean mInEdit;
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!mInEdit) {
mInEdit = true;
String delimiter = " - ";
//Remove chars from your delimiter first
String digits = s.toString().replaceAll("[- ]", "")
.replaceAll("\\d{4}", "$0" + delimiter);
//Handle deletion
int dLength = delimiter.length();
if (before > count && digits.endsWith(delimiter.charAt(dLength - 1)) {
digits = digits.substring(0, digits.length() - dLength);
}
mCardNumber.setText(digits);
mCardNumber.setSelection(mCardNumber.length());
mInEdit = false;
}
}
Here you replace delimiter with what you want to separate digits.
For those still facing trouble with backspace and multiple hyphens -
new TextWatcher()
{
boolean hyphenExists;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (s.length() >= 6 && s.charAt(5) == '-') {
hyphenExists = true;
} else {
hyphenExists = false;
}
Log.d("TAG", "beforeTextChanged " + s.toString());
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d("TAG", "onTextChanged " + s.toString());
}
#Override
public void afterTextChanged(Editable s) {
if (s.length() == 5) {
if (!hyphenExists)
s.append('-');
}
Log.d("TAG", "afterTextChanged " + s.toString());
}
}
You can achieve this with on text changed
in my case, i have to format input like this : xxx xxx-xxxx
i done as given below:
etMobileNumber.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (etMobileNumber.text.length == 3 && count != 0) {
val text = etMobileNumber.getText().toString() + " "
etMobileNumber.setText(text)
etMobileNumber.setSelection(text.length)
} else if (etMobileNumber.text.length == 7 && count != 0) {
val text = etMobileNumber.getText().toString() + "-"
etMobileNumber.setText(text)
etMobileNumber.setSelection(text.length)
}
}
})
and the result is very dynamic on the go while typing.
input- 1234567890
result - 123 456-7890