<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:inputType="numberDecimal"
android:digits="0123456789,"
android:gravity="center"/>
After Defining digits it allow me to use "," but only problem I am facing that, I can enter "," multiple time. I want to restrict user so that he can input only one Decimal separator that is comma "," in my case.
I'm pretty sure it depends on the locale your device is on.
boolean hasComma = false;
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (hasComma && (source.equals(".") || source.equals(",")))
{
return "";
}
return source;
}
};
// set input filter for edit text
editText.setFilters(new InputFilter[]{filter});
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) {
if(!hasComma && s.toString().contains("."))
{
s= replaceComma(s.toString());
editText.setText(s);
editText.setSelection(start + 1);
hasComma =true;
}
}
#Override
public void afterTextChanged(Editable s) {
if (s.toString().contains(",") || s.toString().contains("."))
{
hasComma =true;
}
else {
hasComma = false;
}
}
});
//use this method to replace "." to ","
private CharSequence replaceComma(String s) {
return s.replace('.',',');
}
Related
For example, I have EditText with length limitation of two characters. When the first and second letters entered it's ok. But when we will try to enter a third letter the first letter should be replaced with it. Next letter should replace the second and so on in a circle. How can I do this one.
Try using TextWatcher on your edit text to achieve the goal
editText.addTextChangedListener(new TextWatcher() {
private int lastModifiedIndex = 1;
#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() > 2) {
char toReplace = s.charAt(s.length() - 1);
if (lastModifiedIndex == 0) {
editText.setText("" + s.charAt(lastModifiedIndex) + toReplace);
lastModifiedIndex = 1;
editText.setSelection(s.length());
} else {
editText.setText("" + toReplace + s.charAt(lastModifiedIndex));
lastModifiedIndex = 0;
editText.setSelection(s.length());
}
} else {
lastModifiedIndex = 1;
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
Try this one
editText.addTextChangedListener(new TextWatcher() {
private int charLimit = 5;
private int position = 5;
private String newSequence;
#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() > charLimit ) {
if (position == charLimit) {
newSequence = s.subSequence(s.length()-1, s.length()).toString() +
s.subSequence(1, charLimit);
position = 1;
} else {
position++;
newSequence = s.subSequence(0, position).toString() +
s.subSequence(position+1, s.length());
}
editText.setText(null);
editText.setText(newSequence);
editText.setSelection(position);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
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();
}
}
});
I am using edit text in my code.I need to limit the weight value to 160 .How to achieve this.
This is the XML I'm using
android:id="#+id/txtWeight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:inputType="number"
android:layout_weight="0"
android:background="#drawable/border"
android:padding="5dp"
android:maxLength="3"
android:textSize="15sp"
android:maxLines="1"
android:hint=""
i have taken maxLenght as "3". So user will have option of entering upto 999 . I need to limit to 160.
Do this
InputFilter if = new InputFilter[]{ new InputFilterMinMax("0", "180")}
or customize it
InputFilter filterTwoDecimal = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
return null;
}
};
Try this:
public class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) { }
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
Then on your fragment / activity:
EditText et = (EditText) findViewById(R.id.myEditText);
et.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "180")});
You can add a TextWatcher to your EditText and make changes to it so it won't allow unwanted values
editText.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) {
// TODO Auto-generated method stub
}
});
I want to add a mac address to my database via EditText.
Is it possible to add a colon (:) after every second character?
The colon should be displayed directly in the EditText.
EDIT: Tried it. And I think I am on the right way ( your anwers confirm this :P )
inputMac = (EditText) view.findViewById(R.id.editText_mac);
inputMac.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.length() == 2 || s.length() == 5 || s.length() == 7 || s.length() == 9 || s.length() == 12 ){
inputMac.setText(inputMac.getText() + ":");
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
But now after 12 characters I get e.g. 123456789123:::::
I've already answered a similar question, so this is how you can achieve it:
String mTextValue;
Character mLastChar = '\0'; // init with empty character
int mKeyDel;
myEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
boolean flag = true;
String eachBlock[] = myEditText.getText().toString().split(":");
for (int i = 0; i < eachBlock.length; i++) {
if (eachBlock[i].length() > 6) {
flag = false;
}
}
if (flag) {
myEditText.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL)
mKeyDel = 1;
return false;
}
});
if (mKeyDel == 0) {
if (((myEditText.getText().length() + 1) % 3) == 0) {
myEditText.setText(myEditText.getText() + ":");
myEditText.setSelection(myEditText.getText().length());
}
mTextValue = myEditText.getText().toString();
} else {
mTextValue = myEditText.getText().toString();
if (mLastChar.equals(':')) {
mTextValue = mTextValue.substring(0, mTextValue.length() - 1);
myEditText.setText(mTextValue);
myEditText.setSelection(mTextValue.length());
}
mKeyDel = 0;
}
} else {
myEditText.setText(mTextValue);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (s.length()>0) {// save the last char value
mLastChar = s.charAt(s.length() - 1);
} else {
mLastChar = '\0';
}
}
#Override
public void afterTextChanged(Editable s) {}
});
PS: It also handle deleting characters.
I tried I think I found a way wich is not that complicated. (Its not perfect but I think I will make it)
inputMac.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
macLengthBefore = inputMac.length();
Log.d("Textlänge BEFORE", macLengthBefore.toString());
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
macLengthAfter = inputMac.length();
Log.d("Textlänge AFTER", macLengthAfter.toString());
if (macLengthAfter > macLengthBefore && ((inputMac.getText().length() + 1) % 3 == 0) && inputMac.length() <= 15) {
inputMac.setText(inputMac.getText() + ":");
inputMac.setSelection(inputMac.getText().length());
}
}
});
Thanks #Rami for modulo query
After few trial and errors I was able to write a simple and working code:
mEditText.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().length() < 17) && ((before == 1 && count == 2) || (before == 4
&& count == 5))) {
String string = mEditText.getText().toString();
string = string.concat(":");
mEditText.setText(string);
mEditText.setSelection(string.length());
}
}
});
Below code goes into your xml file:
<EditText
android:id="#+id/edit_text"
style="#style/textfield_wh"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="17"
android:digits="abcdefABCDEF0123456789:"
android:inputType="text" />
Try this,
editText1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
*****APPLY YOUR LOGIC HERE*****
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
I have an edittext, and a textwatcher that watches if SPACE arrived or not. If its a SPACE I would like to delete that instantly. Or if its a space I want to make sure it doesnt appear but indicate somehow (seterror, toast) for the user that space is not allowed.
edittext.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) {}
});
I cannot define onkeydown in the afterTextChaned method, since it gives me an error.
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_SPACE) {
}
}
So it is not working (syntax error, misplaced construct for the int keyCode.
Thanks you in advance!
The solution is as usually much simpler:
#Override
public void afterTextChanged(Editable s) {
String result = s.toString().replaceAll(" ", "");
if (!s.toString().equals(result)) {
ed.setText(result);
ed.setSelection(result.length());
// alert the user
}
}
This shouldn't have the problems of the previous attempts.
setSelection is there to set the cursor again at the end of your EditText:
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {}
#Override
public void beforeTextChanged(CharSequence s, int arg1, int arg2,
int arg3) {}
#Override
public void afterTextChanged(Editable arg0) {
if(editText.getText().toString().contains(" ")){ editText.setText(editText.getText().toString().replaceAll(" " , ""));
editText.setSelection(editText.getText().length());
Toast.makeText(getApplicationContext(), "No Spaces Allowed", Toast.LENGTH_LONG).show();
}
}});
boolean editclicked =false ;
edittext.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
editclicked = false ;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
editclicked = true;
});
Put this as a separate function:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (editclicked) {
if (keyCode == KeyEvent.KEYCODE_SPACE) {
return false
}
} else {
super.onKeyDown(keyCode, event);
}
}
#Override
public void afterTextChanged(Editable s) {
String result = s.toString().replaceAll("\\s", "");
if (!s.toString().equals(result)) {
int pos = editText.getSelectionStart() - (s.length() - result.length());
editText.setText(result);
editText.setSelection(Math.max(0,Math.min(pos, result.length())));
editText.setError("No spaces allowed");
}
}
\s matches any whitespace character (equal to [\r\n\t\f\v ])
Setting selection like this, allow you to enter or paste text in middle of edittext without loosing cursor position
My relatively simple solution for instant whitespace deletion without removing spannables (styles) in EditText:
Remove at start:
#Override
public void afterTextChanged(Editable s) {
int i;
for (i = 0; i < s.length() && Character.isWhitespace(s.charAt(i)); i++) { ; }
s.replace(0, i, "");
}
Basically that's it, but you can also do:
Remove at start (without interrupting first input):
#Override
public void afterTextChanged(Editable s) {
String text = s.toString();
if(!text.trim().isEmpty()){
int i;
for (i = 0; i < s.length() && Character.isWhitespace(s.charAt(i)); i++) { ; }
s.replace(0, i, "");
}
}
Removing at start and end (allow 1 whitespace at end for convinient input):
#Override
public void afterTextChanged(Editable s) {
int i;
//remove at start
for (i = 0; i < s.length() && Character.isWhitespace(s.charAt(i)); i++) { ; }
s.replace(0, i, "");
//remove at end, but allow one whitespace character
for (i = s.length(); i > 1 && Character.isWhitespace(s.charAt(i-1)) && Character.isWhitespace(s.charAt(i-2)); i--) { ; }
s.replace(i, s.length(), "");
}
For removing the space instantly you can achieve it by two ways.
One simple solution you can set the digits to your edit text.
android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
second way you can set a filter
EditText.setFilters(new InputFilter[] { filter });
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (Character.isSpaceChar(source.charAt(i))) {
return "";
}
}
return null;
}
}
One more simple way to achieve this using the input Filter
editText.setFilters(new InputFilter[]{new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source.toString().equalsIgnoreCase(" ")){
return "";
}
return source;
}
}});
This will remove the space entered by the user immediately and gives appearance like space is disabled.