Clear EditText data inside beforeTextChanged() of TextWatcher - android

I have to watch EditText in my App in such a way that if in EditText data is in 2 lines
then again I want to write in 3rd line then previous 2 line's data should get clear.
For this I am using following way to do
mTextWatcher = new TextWatcher() {
private int lines;
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
Log.v("", "inside ontextchnaged");
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
lines = getTotalLines(txtDataSource);
if (lines == 2) {
txtDataSource.removeTextChangedListener(mTextWatcher);
Log.v("", txtDataSource.getText().toString());
txtDataSource.setText("");
txtDataSource.addTextChangedListener(mTextWatcher);
}
}
#Override
public void afterTextChanged(Editable s) {
Log.v("", "inside aftertextchanged");
}
};
txtDataSource.addTextChangedListener(mTextWatcher);
and I am getting no of lines enter by the below code
private int getTotalLines(EditText editText) {
int lineNumber = 0;
String text = editText.getText().toString()
.substring(0, editText.getSelectionStart());
for (int i = 0; i < text.length(); i++) {
if (String.valueOf(text.charAt(i)).equalsIgnoreCase("\n")) {
lineNumber++;
}
}
return lineNumber;
}
So when i m getting 2 lines data in EditText then I am removing watcher from EditText
then clearing data of EditText and again I added watcher on EditText .
Every thing working fine but problem is after 2 lines when I start to wrote then it is not writing first character which I enter from Keypad it starts writing from second character input.
So after 2 lines when enter 2 characters then it didnt write first char which i enter it starts writing from second character.
Please help me to resolve this.
Thanks ....

Finally I solved my issue.
It may not be standard way to do, but I didn't find any other way to do this inside
beforeTextChanged()
I solved using the below code inside onTextChanged()
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
lines = getTotalLines(txtDataSource);
if (lines == 2 ) {
String frstChar = String.valueOf(s.toString().charAt(s.toString().length() - 1));
txtDataSource.removeTextChangedListener(mTextWatcher);
txtDataSource.setText("" + frstChar);
txtDataSource.setSelection(txtDataSource.getText().toString().length());
txtDataSource.addTextChangedListener(mTextWatcher);
}
}
and now in 3rd line first character is getting displayed in EditText.
I am sharing my way so that if someone else would face such issue they can solve by this way..
Thanks

Try to solve the problem when you edit from the middle of the word.
"setSelection" keeps forcing you to write at the end of the text.

Related

TextWatcher monitor only current input

I have EditText which is connected with TextWatcher I'm monitoring when user presses # letter. That will make a Listview appear with names of commentators on particular post. When user chooses one of the users from ListView, name is append to EditText and ListView is hidden.
But the problem is when user continues typing ListView will appear again because afterTextChanged(Editable s) monitors the whole inputted text which already contains letter #.
Is there a way to monitor only what user is actually typing not the whole inputed text? Or somehow escape last inputed word in TextWatcher? Or any other suggestions how to solve this.
I was researching but didn't find anything useful.
Thanks in advance
There can be many ways to achieve this. This is one of them. You can check weather your list is already filled or not.
final boolean isListSet = false;
public static final String textToFind = "#";
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) {
}
#Override
public void afterTextChanged(Editable s) {
if (!isListSet && s.toString().contains(textToFind)) {
// set your list here
isListSet = true;
}
if (!s.toString().contains(textToFind)) {
// remove your list
isListSet = false;
}
}
});

Best way to get int from user

I'm needing to get an integer from the user for one of my apps and I have tried using a text edit but it didn't seem to work, so I'm wanting to know another way of getting an integer from the user. The int will be positive numbers only and no more than 2 digits.
Use EditText
You can limit the number of digits like this
Update:
Then you need to add a listener
http://developer.android.com/reference/android/widget/TextView.html#addTextChangedListener(android.text.TextWatcher)
a relevant question:
android edittext onchange listener
You have to use EditText.. then from in Your Activity
String s = ed.getText().ToString();
int i = 0;
if(s!=null)
i= Integer.valueOf(s);
To make sure keyboard only show numbers,
make sure you add
android:input="number"
to your EditText in the XML
UPDATE
yourEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
String s = yourEditText.getText().ToString();
int i = 0;
if(s!=null)
i= Integer.valueOf(s);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
you can use properties in your XML .
use this line to limit input text in numbers in XML :
android:inputType="number"
and use this line to set your specific character:
android:digits="1234567890"
i think it is the best way for this purpose.

Text watcher in edit text is making the edittext slow

In my tablet app I have used fragments and one fragment has multiple Edittexts, and I have a linear layout which will add a sublayout as many times the user wishes to add, in that fragment
This sublayout has two edittext, both this edittext is having
addtextchangelistener(Textwatcher) and
onfocuschangelistner
every time the text is changed 3 conditions are checked in both the edittext
every time the focus is changed 2 conditions are checked in both the edittext
After doing all this condition check, the problem I'm facing is, the edittext typing is too slow, its like i type an email and the whole email gets completely typed after 5 secs or more,
This is the code for 1 edit text in the sublayout:
receiverName.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View paramView, boolean hasFocus) {
receivernameFocus = hasFocus;
if(hasFocus)
{
if(receiverName.getText().toString().length()>0)
ReceiverName_btn_cancel.setVisibility(View.VISIBLE);
else
ReceiverName_btn_cancel.setVisibility(View.INVISIBLE);
}
else
ReceiverName_btn_cancel.setVisibility(View.INVISIBLE);
}
});
receiverName.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence paramCharSequence, int paramInt1,int paramInt2, int paramInt3) {
if(receivernameFocus)
{
if(receiverName.getText().toString().length()>0)
{
receiverNamePresent = true;
ReceiverName_btn_cancel.setVisibility(View.VISIBLE);
}
else
{
receiverNamePresent = false;
ReceiverName_btn_cancel.setVisibility(View.INVISIBLE);
}
}
else
ReceiverName_btn_cancel.setVisibility(View.INVISIBLE);
if(receiverEmailPresent && receiverNamePresent)
addReceiver.setBackgroundResource(R.drawable.plus_receiver);
else
addReceiver.setBackgroundResource(R.drawable.plus_deselect_receiver);
}
#Override
public void beforeTextChanged(CharSequence paramCharSequence,
int paramInt1, int paramInt2, int paramInt3) {
}
#Override
public void afterTextChanged(Editable paramEditable) {
}
});
same conditions are present for the other edittext, and everytime the user inflate another view, same set of edittext will be created for the new view too.
I can't remove the conditions, all of them are necessary, and you can see its just some button visibility or setting background resource
How to optimize this code, or how to speed up the edittext typing speed for android tablet?
EDIT: If I'm typing 10 letters persecond its showing only 1 letter per second in the edittext(so all the 10 letters will be visible in the edittext after 10 seconds), which I believe is happening because of multiple condition checking within onTextChanged method, the delay in showing the text is too much for user experience.
How to make the edittext show the text as fast as I'm typing it
Thanks
Here public void onTextChanged(CharSequence paramCharSequence, int paramInt1,int paramInt2, int paramInt3) it's generally in this format:
public void onTextChanged(CharSequence s, int start, int before, int count)
So here you will need to do some operation using paramInt3 . If you would like to show suggest text will come after you enter 3 letter then perform an operation here in this manner:
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (count%3 == 1)
{
adapter.clear();
GetPlaces task = new GetPlaces();
task.execute(dep_place.getText().toString());
}
}
here I haved updated text from server side in background. You just need to modify this portion from where your text will come use this code here.
Thanks.

prevent keyboard from automatically switching to text mode

I have an edit text which accepts both text and numeric values.
I have to format it with appending space after every 4 characters.
here are the steps to replicate the issue
1. tap on the edit text
2. select number mode on the keypad and keep entering numbers
3. the moment space is appended, the keyboard switches to text mode. how do I prevent it. Here is the code I tried
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)
{
String text = editText.getText().toString();
textlength = editText.getText().length();
if(text.endsWith(" "))
return;
if(textlength == 5 || textlength == 10 || textlength == 20)
{
editText.setText(new StringBuilder(text).insert(text.length()-1, " ").toString());
editText.setSelection(editText.getText().length());
}
}});
}
What you can try to do is in your program
a) Check if space character is received. If yes
b) Switch to numeric keypad using the function setInputType(InputType.TYPE_CLASS_NUMBER)
Hopefully this will solve the issue. But you will need to be monitoring each character input by user.

Override the default behavior of Backspace in AutoCompleteTextView

I'm using a AutoCompleteTextView, the default behavior of the backspace button goes something like this.
Say i type "Ar", this gives me a suggestion "Argentina", i select "Argentina" from the drop down...The Text now becomes "Argentina ". But say i need to remove the last character, so I hit backspace on the keyboard, the AutcompleteTextView removes all the text till the point i typed (ie. the text now becomes "Ar" again).
How do i eliminate this behavior and let the text in the AutoComplete to behave normally?
At first I thought it was some kind of SpannableString so i called "clearSpans()" but it doesn't seem to work. Any pointers?
Thanks in advance. :)
I think you use the MultiAutoCompleteTextView which add the setTokenizer(new SpaceTokenizer()).
If you use
AutoCompleteTextView instead of MultiAutoCompleteTextView and remove the setTokenizer(...)
the problem will be gone.
I did not find any solution, but finally I figured out, this code worked for me:
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
// removing QwertyKeyListener.Replaced span
Editable text = editText.getText();
Object[] spans = text.getSpans(0, text.length(), Object.class);
if (spans != null) {
for (int i = spans.length - 1; i >= 0; i--) {
Object o = spans[i];
String desc = "" + o; // This is a hack, not a perfect solution, but works. "QwertyKeyListener.Replaced" is a private type
if (desc.indexOf("QwertyKeyListener$Replaced") != -1) {
text.removeSpan(o);
}
}
}
} catch (Throwable e) {
MyUtil.msgError(e);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});

Categories

Resources