using setText() don't want to call textwatcher events? [duplicate] - android

I have a ListView where each row has an EditText control. I want to add a TextChangedListener to each row; one that contains extra data which says which row the EditText was in. The problem is that as getView gets called, multiple TextWatchers are added; because the convertView already having a TextWatcher (and one that points to a different row).
MyTextWatcher watcher = new MyTextWatcher(currentQuestion);
EditText text = (EditText)convertView.findViewById(R.id.responseText);
text.addTextChangedListener(watcher);
MyTextWatcher is my class that implements TextWatcher; and handles the text events. CurrentQuestion lets me know which row I'm acting upon. When I type in the box; multiple instances of TextWatcher are called.
Is there any way to remove the TextWatchers before adding the new one? I see the removeTextChangedListener method, but that requires a specific TextWatcher to be passed in, and I don't know how to get the pointer to the TextWatcher that is already there.

There is no way to do this using current EditText interface directly. I see two possible solutions:
Redesign your application so you always know what TextWatcher are added to particular EditText instance.
Extend EditText and add possibility to clear all watchers.
Here is an example of second approach - ExtendedEditText:
public class ExtendedEditText extends EditText
{
private ArrayList<TextWatcher> mListeners = null;
public ExtendedEditText(Context ctx)
{
super(ctx);
}
public ExtendedEditText(Context ctx, AttributeSet attrs)
{
super(ctx, attrs);
}
public ExtendedEditText(Context ctx, AttributeSet attrs, int defStyle)
{
super(ctx, attrs, defStyle);
}
#Override
public void addTextChangedListener(TextWatcher watcher)
{
if (mListeners == null)
{
mListeners = new ArrayList<TextWatcher>();
}
mListeners.add(watcher);
super.addTextChangedListener(watcher);
}
#Override
public void removeTextChangedListener(TextWatcher watcher)
{
if (mListeners != null)
{
int i = mListeners.indexOf(watcher);
if (i >= 0)
{
mListeners.remove(i);
}
}
super.removeTextChangedListener(watcher);
}
public void clearTextChangedListeners()
{
if(mListeners != null)
{
for(TextWatcher watcher : mListeners)
{
super.removeTextChangedListener(watcher);
}
mListeners.clear();
mListeners = null;
}
}
}
And here is how you can use ExtendedEditText in xml layouts:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ua.inazaruk.HelloWorld.ExtendedEditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="header"
android:gravity="center" />
</LinearLayout>

You can remove TextWatcher from your EditText. First of all I suggest you to move TextWatcher declaration outside the the editText.addTextChangedListener(...):
protected TextWatcher yourTextWatcher = new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// your logic here
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// your logic here
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// your logic here
}
};
After that you will be able to set TextWather little bit simpler:
editText.addTextChangedListener(yourTextWatcher);
Than you can remove TextWatcher like this:
editText.removeTextChangedListener(yourTextWatcher);
and set another if you want.

I also spent a lot of time finding the solution and finally ended up solving with the help of tag like below.
It would remove previous TextWatcher instances by getting references from tag of the convertView.
It perfectly solves the problem.
In your CustomAdapter file, set a new inner class like below:
private static class ViewHolder {
private TextChangedListener textChangedListener;
private EditText productQuantity;
public EditText getProductQuantity() {
return productQuantity;
}
public TextChangedListener getTextChangedListener() {
return textChangedListener;
}
public void setTextChangedListener(TextChangedListener textChangedListener) {
this.textChangedListener = textChangedListener;
}
}
Then in your overrided public View getView(int position, View convertView, ViewGroup parent) method implement the logic like below:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
EditText productQuantity;
TextChangedListener textChangedListener;
if(convertView==null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.cart_offer_item, parent, false);
productQuantity=(EditText)convertView.findViewById(R.id.productQuantity);
addTextChangedListener(viewHolder, position);
convertView.setTag(viewHolder);
}
else
{
ViewHolder viewHolder=(ViewHolder)convertView.getTag();
productQuantity=viewHolder.getProductQuantity();
removeTextChangedListener(viewHolder);
addTextChangedListener(viewHolder, position);
}
return convertView;
}
private void removeTextChangedListener(ViewHolder viewHolder)
{
TextChangedListener textChangedListener=viewHolder.getTextChangedListener();
EditText productQuantity=viewHolder.getProductQuantity();
productQuantity.removeTextChangedListener(textChangedListener);
}
private void addTextChangedListener(ViewHolder viewHolder, int position)
{
TextChangedListener textChangedListener=new TextChangedListener(position);
EditText productQuantity=viewHolder.getProductQuantity();
productQuantity.addTextChangedListener(textChangedListener);
viewHolder.setTextChangedListener(textChangedListener);
}
Then implement TextWatcher class as below:
private class TextChangedListener implements TextWatcher
{
private int position;
TextChangedListener(int position)
{
this.position=position;
}
#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) {
Log.d("check", "text changed in EditText");
}
}
It would remove previous TextWatcher instances by getting references from tag of the convertView

I struggled with a similar problem with a lot of EditTexts in RecyclerView. I solved it by reflection. Call ReflectionTextWatcher.removeAll(your_edittext) before bind views. This piece of code finds all TextWatchers and removes them from the local EditText's list called "mListeners".
public class ReflectionTextWatcher {
public static void removeAll(EditText editText) {
try {
Field field = findField("mListeners", editText.getClass());
if (field != null) {
field.setAccessible(true);
ArrayList<TextWatcher> list = (ArrayList<TextWatcher>) field.get(editText); //IllegalAccessException
if (list != null) {
list.clear();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static Field findField(String name, Class<?> type) {
for (Field declaredField : type.getDeclaredFields()) {
if (declaredField.getName().equals(name)) {
return declaredField;
}
}
if (type.getSuperclass() != null) {
return findField(name, type.getSuperclass());
}
return null;
}
}
I hope, this will help someone.

Save the current textwatcher in viewholder and you can find the one you want to remove.

It has been long since this question was asked, but someone might find this useful. The problem with TextWatcher in Recyclerview is that we have to make sure it is removed before the view is recycled. Otherwise, we loss the instance of the TextWatcher, and calling removeTextChangedListener(textWatcher) in the OnBindViewHolder() will only remove the current instance of TextWatcher.
The way I solve this problem is to add the TextChangedListener inside a FocusChangedListener:
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus) {
editText.addTextChangedListener(textWatcher)
}
else{
editText.removeTextChangedListener(textWatcher)
}
}
});
This way I am sure when the editText doesn't have focus then the textwatcher is removed, and added again when it has focus. So, when the recyclerview is recycled the editText will have any textChangeListener removed.

As you can see here: CodeSearch of TextView there is no way of removing all listeners. The only way is to provide the watcher you used to register it.
I do not yet fully understand why there are other listeners already registered. However you can subclass the EditText, override the addTextChangedListener(..) and in it keep a copy of all added references yourself and then delegate to the superclass implementation. You then can also provide an additional method that removes all listeners.
Get in touch if you need further explanations.

I had the same problem with xamarin/C# and I wrote for this a class to manage click events inside a ListView where the item view will be "recycled":
public class ViewOnClickEventHandler: Java.Lang.Object
{
private List<EventHandler> EventList { get; set; }
public void SetOnClickEventHandler(View view, EventHandler eventHandler)
{
if (view.Tag != null)
{
ViewOnClickEventHandler holder = ((ViewOnClickEventHandler)view.Tag);
foreach (EventHandler evH in holder.EventList)
view.Click -= evH;
for (int i = 0; i < holder.EventList.Count; i++)
holder.EventList[i] = null;
holder.EventList.Clear();
}
EventList = new List<EventHandler>();
EventList.Add(eventHandler);
view.Click += eventHandler;
view.Tag = this;
}
}
You can use it in your ListView BaseAdapter GetItem method this way:
TextView myTextView = convertView.FindViewById<TextView>(Resource.Id.myTextView);
ViewOnClickEventHandler onClick = new ViewOnClickEventHandler();
onClick.SetOnClickEventHandler(myTextView, new EventHandler(delegate (object sender, EventArgs e)
{
// Do whatever you want with the click event
}));
The ViewOnClickEventHandler class will care about multiple events on your textview. You can also change the class for textchange events. It's the same princip.
I hope this will help.
bye,
nxexo007

I resolved this situation without extend TextView class.
private ArrayList<TextWatcher> mEditTextWatcherList = new ArrayList<>();
private TextWatcher mTextWatcher1;
private TextWathcer mTextWatcher2;
mTextWathcer1 = 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) {}
};
mTextWathcer2 = 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) {}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
setListener(mTextWatcher1);
setListener(mTextWatcher2);
removeListeners();
}
private setListener(TextWatcher listener) {
mEditText.addTextChangedListener(listener);
mEditTextWatcherList.add(listener);
}
private removeListeners() {
for (TextWatcher t : mEditTextWatcherList)
mEditText.removeTextChangedListener(t);
mEditTextWatcherList.clear();
}

I struggled with a similar problem. I solved it by saving references to my textWatchers in an ArrayList:
private final List<TextWatcher> textWatchersForProfileNameTextBox = new ArrayList<>();
public void addTextWatcherToProfileNameTextBox(TextWatcher textWatcher){
textWatchersForProfileNameTextBox.add(textWatcher);
getProfileNameTextView().addTextChangedListener(textWatcher);
}
public void removeAllTextWatchersFromProfileNameTextView(){
while (!textWatchersForProfileNameTextBox.isEmpty())
getProfileNameTextView().removeTextChangedListener(textWatchersForProfileNameTextBox.remove(0));
}

If one, like me, deals with ViewHolder, then simply saving a reference to a text watcher upon its creation will not help. Upon reuse the view will get to some other ViewHolder which would not have a reference to that old text watcher, thus one won't be able to delete it.
Personally i chose to solve problem like #inazaruk, though updated code to Kotlin + renamed class to better reflect it's purpose.
class EditTextWithRemovableTextWatchers(context: Context?, attrs: AttributeSet?) : TextInputEditText(context, attrs) {
private val listeners by lazy { mutableListOf<TextWatcher>() }
override fun addTextChangedListener(watcher: TextWatcher) {
listeners.add(watcher)
super.addTextChangedListener(watcher)
}
override fun removeTextChangedListener(watcher: TextWatcher) {
listeners.remove(watcher)
super.removeTextChangedListener(watcher)
}
fun clearTextChangedListeners() {
for (watcher in listeners) super.removeTextChangedListener(watcher)
listeners.clear()
}
}

What I did to remove text watchers is very simple. I created an array to put my textwatchers:
final TextWatcher[] textWatchers = new TextWatcher[3];
I added them in:
final int CURRENT_PIN_CHECK = 0, NEW_PIN = 1, CONFIRM_PIN_CHECK = 2;
textWatchers[CURRENT_PIN_CHECK] = returnTextWatcherCheckPIN(CURRENT_PIN_CHECK);
textWatchers[NEW_PIN] = returnTextWatcherCheckPIN(NEW_PIN);
textWatchers[CONFIRM_PIN_CHECK] = returnTextWatcherCheckPIN(CONFIRM_PIN_CHECK);
My returnTextWatcherCheckPIN method instantiates a textWatcher with a different checker (switchMethod to check all four editTexts) on afterTextChanged.
Then whenever I remove a text watcher I just referenced the one from the array:
etPin4.removeTextChangedListener(textWatchers[CURRENT_PIN_CHECK]);
Check the listeners size of the editText on debug:
It's removed! That solved my problem!

I've run into the issue when using EditText in ViewHolder in RecyclerView item, and it was causing error of infinite loop, when ViewHolder was binding, cause the TextWatcher added in previous bind call was called, hence, never-ending loop..
The only working solution for that was to store TextWatcher's in the list, and then in onBindViewHolder, go trough that list and remove TextWatcher from the EditText.
private val textWatchers: MutableList<TextWatcher> = mutableListOf()
Add TextWatcher to list before assigning it to EditText:
textWatchers.add(textWatcher1)
vh.moneyAmount.editText?.addTextChangedListener(textWatcher1)
Remove them when binding the item, going to trough the entire textWatcherList:
private fun removeTextWatcher(vh: MoneyItemViewHolder) {
textWatchers.forEach { vh.moneyAmount.editText?.removeTextChangedListener(it) }
}
There isn't any other way to remove the TextWatcher's from EditText, than passing the TextWatcher object, hence it needs to be stored somewhere is we plan to remove it later.

Why not attach the TextWatcher reference to the EditText itself with setTag()?
if (etTagValue.getTag(R.id.textWatcherTag) != null) {
etTagValue.removeTextChangedListener((TextWatcher) etTagValue.getTag());
}
etTagValue.setText(myValue);
TextWatcher textWatcher = new DelayedTextWatcher(text -> meta.setDescription(text.toString()));
etTagValue.addTextChangedListener(textWatcher);
etTagValue.setTag(R.id.textWatcherTag, textWatcher);
In ids.xml under /values package:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="textWatcherTag" type="id" />
</resources>

Related

multiline edittext where parts are not editable, like fill in the blanks

I need to have a view which contains textview and edittext.
Example:
Yay! you made it to ______ We should hang out! feel ____ to follow me.
Above "_____" could be of any length and it should feel like a paragraph in the end. Rest of the text given above is not changeable. Just like fill in the blanks.
From my perspective, a fill-in-the-blank widget should do the following:
Allow only certain identified portions of the text to be changed. The rest of the text is locked.
Not allow cursor movement into the locked text.
Flow from line to line like EditText.
Be generalized with variable placement of blanks.
Here is an implementation of such a widget based upon EditText. Editable spans are set up using a span (BlanksSpan) extended from StyleSpan. A blank span is identified by five underscores ("_____") in the text. Cursor movement is controlled in OnSelectionChanged() and various EditText callbacks. Changes to the text is monitor by a TextWatcher and adjustments to the displayed text are made there.
Here is the video of the widget in use:
FillInBlanksEditText.java
public class FillInBlanksEditText extends android.support.v7.widget.AppCompatEditText
implements View.OnFocusChangeListener, TextWatcher {
private int mLastSelStart;
private int mLastSelEnd;
private BlanksSpan mSpans[];
private Editable mUndoChange;
private BlanksSpan mWatcherSpan;
public FillInBlanksEditText(Context context) {
super(context);
init();
}
public FillInBlanksEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public FillInBlanksEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mSpans = setSpans();
setOnFocusChangeListener(this);
}
#Override
public void onRestoreInstanceState(Parcelable state) {
mSpans = null;
super.onRestoreInstanceState(state);
Editable e = getEditableText();
mSpans = e.getSpans(0, e.length(), BlanksSpan.class);
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
addTextChangedListener(this);
if (findInSpan(getSelectionStart(), getSelectionEnd()) != null) {
mLastSelStart = getSelectionStart();
mLastSelEnd = getSelectionEnd();
} else if (findInSpan(mLastSelStart, mLastSelEnd) == null) {
setSelection(getEditableText().getSpanStart(mSpans[0]));
}
} else {
removeTextChangedListener(this);
}
}
#Override
protected void onSelectionChanged(int selStart, int selEnd) {
if (!isFocused() || mSpans == null ||
(getSelectionStart() == mLastSelStart && getSelectionEnd() == mLastSelEnd)) {
return;
}
// The selection must be completely within a Blankspan.
final BlanksSpan span = findInSpan(selStart, selEnd);
if (span == null) {
// Current selection is not within a Blankspan. Restore selection to prior location.
moveCursor(mLastSelStart);
} else if (selStart > getEditableText().getSpanStart(span) + span.getDataLength()) {
// Acceptable location for selection (within a Blankspan).
// Make sure that the cursor is at the end of the entered data. mLastSelStart = getEditableText().getSpanStart(span) + span.getDataLength();
mLastSelEnd = mLastSelStart;
moveCursor(mLastSelStart);
} else {
// Just capture the placement.
mLastSelStart = selStart;
mLastSelEnd = selEnd;
}
super.onSelectionChanged(mLastSelStart, mLastSelEnd);
}
// Safely move the cursor without directly invoking setSelection from onSelectionChange.
private void moveCursor(final int selStart) {
post(new Runnable() {
#Override
public void run() {
setSelection(selStart);
}
});
// Stop cursor form jumping on move.
getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
getViewTreeObserver().removeOnPreDrawListener(this);
return false;
}
});
}
#Nullable
private BlanksSpan findInSpan(int selStart, int selEnd) {
for (BlanksSpan span : mSpans) {
if (selStart >= getEditableText().getSpanStart(span) &&
selEnd <= getEditableText().getSpanEnd(span)) {
return span;
}
}
return null;
}
// Set up a Blankspan to cover each occurrence of BLANKS_TOKEN.
private BlanksSpan[] setSpans() {
Editable e = getEditableText();
String s = e.toString();
int offset = 0;
int blanksOffset;
while ((blanksOffset = s.substring(offset).indexOf(BLANKS_TOKEN)) != -1) {
offset += blanksOffset;
e.setSpan(new BlanksSpan(Typeface.BOLD), offset, offset + BLANKS_TOKEN.length(),
Spanned.SPAN_INCLUSIVE_INCLUSIVE);
offset += BLANKS_TOKEN.length();
}
return e.getSpans(0, e.length(), BlanksSpan.class);
}
// Check change to make sure that it is acceptable to us.
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
mWatcherSpan = findInSpan(start, start + count);
if (mWatcherSpan == null) {
// Change outside of a Blankspan. Just put things back the way they were.
// Do this in afterTextChaanged. mUndoChange = Editable.Factory.getInstance().newEditable(s);
} else {
// Change is OK. Track data length.
mWatcherSpan.adjustDataLength(count, after);
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Do nothing...
}
#Override
public void afterTextChanged(Editable s) {
if (mUndoChange == null) {
// The change is legal. Modify the contents of the span to the format we want.
CharSequence newContents = mWatcherSpan.getFormattedContent(s);
if (newContents != null) {
removeTextChangedListener(this);
int selection = getSelectionStart();
s.replace(s.getSpanStart(mWatcherSpan), s.getSpanEnd(mWatcherSpan), newContents);
setSelection(selection);
addTextChangedListener(this);
}
} else {
// Illegal change - put things back the way they were.
removeTextChangedListener(this);
setText(mUndoChange);
mUndoChange = null;
addTextChangedListener(this);
}
}
#SuppressWarnings("WeakerAccess")
public static class BlanksSpan extends StyleSpan {
private int mDataLength;
public BlanksSpan(int style) {
super(style);
}
#SuppressWarnings("unused")
public BlanksSpan(#NonNull Parcel src) {
super(src);
}
public void adjustDataLength(int count, int after) {
mDataLength += after - count;
}
#Nullable
public CharSequence getFormattedContent(Editable e) {
if (mDataLength == 0) {
return BLANKS_TOKEN;
}
int spanStart = e.getSpanStart(this);
return (e.getSpanEnd(this) - spanStart > mDataLength)
? e.subSequence(spanStart, spanStart + mDataLength)
: null;
}
public int getDataLength() {
return mDataLength;
}
}
#SuppressWarnings({"FieldCanBeLocal", "unused"})
private static final String TAG = "FillInBlanksEditText";
private static final String BLANKS_TOKEN = "_____";
}
activity_main.java
A sample layout.
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.fillintheblanks.FillInBlanksEditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="#android:color/transparent"
android:inputType="textMultiLine"
android:padding="16dp"
android:text="Yay! You made it to _____. We should hang out! Feel _____ to follow me."
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.example.fillintheblanks.FillInBlanksEditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="#android:color/transparent"
android:inputType="textMultiLine"
android:padding="16dp"
android:text="_____ says that it is time to _____. Are you _____?"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="#id/editText" />
</android.support.constraint.ConstraintLayout>
A few things to note:
In extracted mode, cursor placement jumps around if a touch is made outside of a BlanksSpan. Things still work but misbehave a little.
The length of the blanks fields is fixed, but it can be made variable in length with some additional work.
The action mode in the control needs some work based upon requirements.
multiline edittext where parts are not editable, like fill in the blanks
You can use a TextWatcher() for this requirement
Try this he is the little work around for this
MainActivity
public class MainActivity extends AppCompatActivity {
EditText myEditText;
String startText = "I'm The First Part";
String lastText = "I'm The Last Part";
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SpannableStringBuilder firstStringBuilder = new SpannableStringBuilder(startText);
final SpannableStringBuilder lastStringBuilder = new SpannableStringBuilder(lastText);
StyleSpan firstStyleSpan = new StyleSpan(android.graphics.Typeface.BOLD);
firstStringBuilder.setSpan(firstStyleSpan, 0, firstStringBuilder.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold
lastStringBuilder.setSpan(firstStyleSpan, 0, lastStringBuilder.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold
myEditText = findViewById(R.id.myEditText);
spannableStringBuilder.append(firstStringBuilder);
spannableStringBuilder.append(" ");
spannableStringBuilder.append(lastStringBuilder);
myEditText.setText(spannableStringBuilder);
Selection.setSelection(myEditText.getText(), startText.length() + 1);
myEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
if (!s.toString().startsWith(firstStringBuilder.toString())
|| !s.toString().contains(lastText)) {
Log.e("StringBuilder_TAG", spannableStringBuilder.toString());
myEditText.setText(spannableStringBuilder);
Selection.setSelection(myEditText.getText(), myEditText.getText().length() - lastStringBuilder.length() - 1);
} else {
spannableStringBuilder.clear();
spannableStringBuilder.append(s.toString());
Log.e("My_TAG", spannableStringBuilder.toString());
}
}
});
}
}
layout.activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/myEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:padding="5dp" />
</LinearLayout>
Here is the output video of above code https://www.youtube.com/watch?v=pfhUzLiFD6U
using above code you able to make not editble first and last parts of editext
Note
You can also use a TextDrawable
here are some links for that
How to put text in a drawable?
https://github.com/amulyakhare/TextDrawable
Set unchangeable some part of editText android
You can also create a custom EditText for this
Adding a prefix to an EditText
You can also use InputFilter
Solution one
Try using flexbox-layout - https://github.com/google/flexbox-layout.
Solution Two
Use textWatcher
Solution Three
Use html, css and javascript to design a simple webpage.
Use webview to load the html file.
Follow #Cheticamp 's answer, it works when you set a SpannableString in a setText() method.
Also you should override setText() method and set Spans to mSpans:
#Override
public void setText(CharSequence text, BufferType type) {
mSpans = Editable.Factory.getInstance().newEditable(text).getSpans(0, text.length(), BlanksSpan.class);
Log.d(TAG, "setText: " + mSpans.length);
super.setText(text, type);
}
if you don't set a SpannableString, Editable interface will get a simple String without Spans.
So if you call methods like:
Editable.getSpanStart(tag) returns -1;
Editable.getSpanEnd(tag) returns -1;
Editable.getSpans(start, end, Class) returns empty array

Android - notifyDataSetChanged when I've finished to edit an editText

I'm trying to notifydatasetchanged when I've finished to edit an edit text in a recyclerview (why ? because some others objects in recyclerview are accessible only if for exemple the edit text is equals to "test").
So I have an adapter with many view Holders, here is the one for edit text:
public EditTextViewHolder(View itemView, final Activity activity, final Context context, final String param) {
super(itemView);
this.activity = activity;
this.context = context;
this.param = param;
name = (TextView) itemView.findViewById(R.id.tEditTextName);
desc = (TextView) itemView.findViewById(R.id.tEditTextDescription);
details = (TextView) itemView.findViewById(R.id.tEditTextMoreDetails);
editText = (EditText) itemView.findViewById(R.id.eEditTextValue);
image = (ImageView) itemView.findViewById(R.id.iEditTextImage);
lMain = (LinearLayout) itemView.findViewById(R.id.layoutTaskEditText);
lOptional = (LinearLayout) itemView.findViewById(R.id.layoutEditTextOptional);
lRequired = (LinearLayout) itemView.findViewById(R.id.isRequiredTask);
}
public void setLayout(final Content content) {
name.setText(content.getTitle());
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) {
content.getAnswers().get(0).setValue(s.toString().trim());
}
});
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus)
TaskActivity.sAdapter.notifyDataSetChanged();
}
});
}
But I'm getting the error "Cannot call this method while RecyclerView is computing a layout or scrolling" even if I try to notify in handler or on ui thread it's not working.
It works with all my others view holders. Do you know what am I doing wrong with edit text ?
This exception probably occur when you are calling
notifyItemInserted(position);, notifyItemChanged(position), or
notifyItemRemoved(position); from a background thread (or from a
callback, which runs on a background thread).
To solve this, use Handler in UI Thread:
android.os.Handler mHandler = getActivity().getWindow().getDecorView().getHandler();
mHandler.post(new Runnable() {
public void run(){
//change adapter contents
mRecyclerViewAdapter.notifyItemInserted(position);
}
});
try to call notifyDataSetChanged on adapter instead of activity and also call it inside on UIThread.
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
and make sure inside your adapter has this method with right number of data
#Override
public int getItemCount() {
}

notifyDataSetHasChanged() throws an error when used inside TextWatcher.onTextChanged() inside a RecyclerView

I'm building an app that allows user to have a real time base-conversion of a number. Users input their number in an edit text, and they choose the base using plus and minus button. The problem I encountered so far is providing the real time conversion. All the editText inside the recycler view set their text to a BigInteger that can be converted depending on their base.
My idea was to update the BigInteger as the user is inputting a new number. Therefore every time users input a digit I should be able to update the BigInteger, notify the recycler view that the data as changed and then the edit text views should update automatically. Here's my ConvertViewHolder
public ConvertViewHolder(final View itemView) {
super(itemView);
mBaseTextView = (TextView) itemView.findViewById(R.id.baseLabel);
mEditText = (EditText) itemView.findViewById(R.id.numberEditText);
mMinusButton = (Button) itemView.findViewById(R.id.minusButton);
mPlusButton = (Button) itemView.findViewById(R.id.plusButton);
mRemoveButton = (ImageButton)itemView.findViewById(R.id.removeButton);
mMinusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mRoot.get(getPosition()) > MIN_BASE) {
mRoot.set(getPosition(), (mRoot.get(getPosition()) - 1));
notifyDataSetChanged();
}
}
});
mPlusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mRoot.get(getPosition()) < MAX_BASE){
mRoot.set(getPosition(), (mRoot.get( getPosition() ) +1));
notifyDataSetChanged();
}
}
});
mRemoveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mRoot.remove(getPosition());
notifyDataSetChanged();
}
});
mEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
if(editable.toString().length() > 0) {
// change Big Integer
mNumber.setDecimalNumber(editable.toString(), mRoot.get( getPosition() ) );
// notify change
notifyDataSetChanged();
}
}
});
// TODO: convert numbers at the same time
}
public void bindConverter(final int root){
mBaseTextView.setText(String.format("%02d", root));
// String containing all the allowed digits depending on base
String digits = mNumber.getScaleFromBase(root);
if (root < 11) {
// filter input
mEditText.setInputType(InputType.TYPE_CLASS_NUMBER |
InputType.TYPE_TEXT_FLAG_MULTI_LINE);
mEditText.setKeyListener(DigitsKeyListener.getInstance(digits));
mEditText.setSingleLine(false);
mEditText.setMaxLines(2);
} else {
mEditText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS |
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
mEditText.setSingleLine(false);
mEditText.setMaxLines(2);
mEditText.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);
// TODO: filter input for base higher than 10
}
// set editText to BigInteger displaying it in the correct base
// i.e. if the BigInteger is "8" it will be displayed as 8 if the base is 10
// and as 1000 if the base is 2
mEditText.setText(mNumber.getDecimalNumber(mRoot.get( getPosition() )));
}
}
But apparently I am not allowed to call notifySetDataHasChanged inside the TextWatcher.onTextChanged() as the compiler throws me this error:
java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling
which is pretty self-explanatory, but unfortunately I haven't figured out a possible workaround.
view.post(
new Runnable() {
public void run() { notifyDatasetChanged(); };
}
);
self explanatory:
call this method after RecyclerView compute a layout or scrolling (in next loop)
more explanation:
one thread = code flow synchronous
main thread = looper
looper = message que = runnable = loop
other possible solution ??
call after u exit from recycler view method
ps.
one more hint if this "piece of code" will run more then once pull the runnable in higher stack existence place (in GC scope of RecyclerView) for less usage of resources and computing time :)
private Runnable r = new Runnable {
public void run() { notifyDatasetChanged(); }
}
...
view.post(r);
...
or for generic solution pull in method using interface
public Runnable postNotify(ListAdapter la) {
return = new Runnable {
public void run() { la.notifyDatasetChanged(); }
};
}
...
private Runnable changed = postNotify(adapter);
...
view.pos(changed);

How to know if user made an input without field listeners?

I have an activity with 20 EditTexts on it. I want to display a message if anything has been entered. Instead of attaching 20 listeners to each field, is there a way to know if input has been supplied(data changed)?
Here is an example of a base class that takes care of notifying subclasses if any of their EditText widgets is being used(if any exist). Depending on what you want to do when the user inputs something you may need to change my example to suit your particular case.
Base activity from which you'll inherit:
public abstract class BaseTextWatcherActivity extends Activity {
private TextWatcher mInputObserver = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
onInputChange(s.toString());
}
};
private boolean mOptimize = false;
#Override
public void setContentView(int layoutResID) {
View content = getLayoutInflater().inflate(layoutResID, null);
initInputsObservers((ViewGroup) content);
mOptimize = true;
super.setContentView(content);
}
#Override
public void setContentView(View view) {
if (view instanceof EditText) {
((EditText) view).addTextChangedListener(mInputObserver);
} else if (view instanceof ViewGroup && !mOptimize) {
initInputsObservers((ViewGroup) view);
mOptimize = false;
}
super.setContentView(view);
}
/**
* Implement this method to allow your activities to get notified when one
* of their {#link EditText} widgets receives input from the user.
*
* #param s the string that was entered by the user in one of the EditTexts.
*/
public abstract void onInputChange(String s);
/**
* This will recursively go through the entire content view and add a
* {#link TextWatcher} to every EditText widget found.
*
* #param root
* the content view
*/
private void initInputsObservers(ViewGroup root) {
final int count = root.getChildCount();
for (int i = 0; i < count; i++) {
final View child = root.getChildAt(i);
if (child instanceof EditText) {
((EditText) child).addTextChangedListener(mInputObserver);
} else if (child instanceof ViewGroup) {
initInputsObservers((ViewGroup) child);
}
}
}
}
Then all you have to do in your activities is implement the onInputchange callback to let you know that the user entered something in one of the EditTexts from the current layout. You may want to look at the key event callbacks from the activity class for something simpler, but if I'm not mistaken those events are consumed by the TextView/EditText widgets.
Have your TextViews all call the addTextChangedListener() giving them your Activity as an argument (this). Have your Activity implement TextWatcher and override afterTextChanged().
Whenever one of the TextView changes, afterTextChanged() will be called.
Here is an idea of what your code should look like
public class YouActivity extends Activity implements TextWatcher{
#Override
public void onCreate(Bundle savedInstanceState)
{
[...]
textView1.addTextChangedListener(this);
textView2.addTextChangedListener(this);
[...]
}
#Override
public void afterTextChanged (Editable s)
{
//do something
}
}

How to remove all listeners added with addTextChangedListener

I have a ListView where each row has an EditText control. I want to add a TextChangedListener to each row; one that contains extra data which says which row the EditText was in. The problem is that as getView gets called, multiple TextWatchers are added; because the convertView already having a TextWatcher (and one that points to a different row).
MyTextWatcher watcher = new MyTextWatcher(currentQuestion);
EditText text = (EditText)convertView.findViewById(R.id.responseText);
text.addTextChangedListener(watcher);
MyTextWatcher is my class that implements TextWatcher; and handles the text events. CurrentQuestion lets me know which row I'm acting upon. When I type in the box; multiple instances of TextWatcher are called.
Is there any way to remove the TextWatchers before adding the new one? I see the removeTextChangedListener method, but that requires a specific TextWatcher to be passed in, and I don't know how to get the pointer to the TextWatcher that is already there.
There is no way to do this using current EditText interface directly. I see two possible solutions:
Redesign your application so you always know what TextWatcher are added to particular EditText instance.
Extend EditText and add possibility to clear all watchers.
Here is an example of second approach - ExtendedEditText:
public class ExtendedEditText extends EditText
{
private ArrayList<TextWatcher> mListeners = null;
public ExtendedEditText(Context ctx)
{
super(ctx);
}
public ExtendedEditText(Context ctx, AttributeSet attrs)
{
super(ctx, attrs);
}
public ExtendedEditText(Context ctx, AttributeSet attrs, int defStyle)
{
super(ctx, attrs, defStyle);
}
#Override
public void addTextChangedListener(TextWatcher watcher)
{
if (mListeners == null)
{
mListeners = new ArrayList<TextWatcher>();
}
mListeners.add(watcher);
super.addTextChangedListener(watcher);
}
#Override
public void removeTextChangedListener(TextWatcher watcher)
{
if (mListeners != null)
{
int i = mListeners.indexOf(watcher);
if (i >= 0)
{
mListeners.remove(i);
}
}
super.removeTextChangedListener(watcher);
}
public void clearTextChangedListeners()
{
if(mListeners != null)
{
for(TextWatcher watcher : mListeners)
{
super.removeTextChangedListener(watcher);
}
mListeners.clear();
mListeners = null;
}
}
}
And here is how you can use ExtendedEditText in xml layouts:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ua.inazaruk.HelloWorld.ExtendedEditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="header"
android:gravity="center" />
</LinearLayout>
You can remove TextWatcher from your EditText. First of all I suggest you to move TextWatcher declaration outside the the editText.addTextChangedListener(...):
protected TextWatcher yourTextWatcher = new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// your logic here
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// your logic here
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// your logic here
}
};
After that you will be able to set TextWather little bit simpler:
editText.addTextChangedListener(yourTextWatcher);
Than you can remove TextWatcher like this:
editText.removeTextChangedListener(yourTextWatcher);
and set another if you want.
I also spent a lot of time finding the solution and finally ended up solving with the help of tag like below.
It would remove previous TextWatcher instances by getting references from tag of the convertView.
It perfectly solves the problem.
In your CustomAdapter file, set a new inner class like below:
private static class ViewHolder {
private TextChangedListener textChangedListener;
private EditText productQuantity;
public EditText getProductQuantity() {
return productQuantity;
}
public TextChangedListener getTextChangedListener() {
return textChangedListener;
}
public void setTextChangedListener(TextChangedListener textChangedListener) {
this.textChangedListener = textChangedListener;
}
}
Then in your overrided public View getView(int position, View convertView, ViewGroup parent) method implement the logic like below:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
EditText productQuantity;
TextChangedListener textChangedListener;
if(convertView==null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.cart_offer_item, parent, false);
productQuantity=(EditText)convertView.findViewById(R.id.productQuantity);
addTextChangedListener(viewHolder, position);
convertView.setTag(viewHolder);
}
else
{
ViewHolder viewHolder=(ViewHolder)convertView.getTag();
productQuantity=viewHolder.getProductQuantity();
removeTextChangedListener(viewHolder);
addTextChangedListener(viewHolder, position);
}
return convertView;
}
private void removeTextChangedListener(ViewHolder viewHolder)
{
TextChangedListener textChangedListener=viewHolder.getTextChangedListener();
EditText productQuantity=viewHolder.getProductQuantity();
productQuantity.removeTextChangedListener(textChangedListener);
}
private void addTextChangedListener(ViewHolder viewHolder, int position)
{
TextChangedListener textChangedListener=new TextChangedListener(position);
EditText productQuantity=viewHolder.getProductQuantity();
productQuantity.addTextChangedListener(textChangedListener);
viewHolder.setTextChangedListener(textChangedListener);
}
Then implement TextWatcher class as below:
private class TextChangedListener implements TextWatcher
{
private int position;
TextChangedListener(int position)
{
this.position=position;
}
#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) {
Log.d("check", "text changed in EditText");
}
}
It would remove previous TextWatcher instances by getting references from tag of the convertView
I struggled with a similar problem with a lot of EditTexts in RecyclerView. I solved it by reflection. Call ReflectionTextWatcher.removeAll(your_edittext) before bind views. This piece of code finds all TextWatchers and removes them from the local EditText's list called "mListeners".
public class ReflectionTextWatcher {
public static void removeAll(EditText editText) {
try {
Field field = findField("mListeners", editText.getClass());
if (field != null) {
field.setAccessible(true);
ArrayList<TextWatcher> list = (ArrayList<TextWatcher>) field.get(editText); //IllegalAccessException
if (list != null) {
list.clear();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static Field findField(String name, Class<?> type) {
for (Field declaredField : type.getDeclaredFields()) {
if (declaredField.getName().equals(name)) {
return declaredField;
}
}
if (type.getSuperclass() != null) {
return findField(name, type.getSuperclass());
}
return null;
}
}
I hope, this will help someone.
Save the current textwatcher in viewholder and you can find the one you want to remove.
It has been long since this question was asked, but someone might find this useful. The problem with TextWatcher in Recyclerview is that we have to make sure it is removed before the view is recycled. Otherwise, we loss the instance of the TextWatcher, and calling removeTextChangedListener(textWatcher) in the OnBindViewHolder() will only remove the current instance of TextWatcher.
The way I solve this problem is to add the TextChangedListener inside a FocusChangedListener:
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus) {
editText.addTextChangedListener(textWatcher)
}
else{
editText.removeTextChangedListener(textWatcher)
}
}
});
This way I am sure when the editText doesn't have focus then the textwatcher is removed, and added again when it has focus. So, when the recyclerview is recycled the editText will have any textChangeListener removed.
As you can see here: CodeSearch of TextView there is no way of removing all listeners. The only way is to provide the watcher you used to register it.
I do not yet fully understand why there are other listeners already registered. However you can subclass the EditText, override the addTextChangedListener(..) and in it keep a copy of all added references yourself and then delegate to the superclass implementation. You then can also provide an additional method that removes all listeners.
Get in touch if you need further explanations.
I had the same problem with xamarin/C# and I wrote for this a class to manage click events inside a ListView where the item view will be "recycled":
public class ViewOnClickEventHandler: Java.Lang.Object
{
private List<EventHandler> EventList { get; set; }
public void SetOnClickEventHandler(View view, EventHandler eventHandler)
{
if (view.Tag != null)
{
ViewOnClickEventHandler holder = ((ViewOnClickEventHandler)view.Tag);
foreach (EventHandler evH in holder.EventList)
view.Click -= evH;
for (int i = 0; i < holder.EventList.Count; i++)
holder.EventList[i] = null;
holder.EventList.Clear();
}
EventList = new List<EventHandler>();
EventList.Add(eventHandler);
view.Click += eventHandler;
view.Tag = this;
}
}
You can use it in your ListView BaseAdapter GetItem method this way:
TextView myTextView = convertView.FindViewById<TextView>(Resource.Id.myTextView);
ViewOnClickEventHandler onClick = new ViewOnClickEventHandler();
onClick.SetOnClickEventHandler(myTextView, new EventHandler(delegate (object sender, EventArgs e)
{
// Do whatever you want with the click event
}));
The ViewOnClickEventHandler class will care about multiple events on your textview. You can also change the class for textchange events. It's the same princip.
I hope this will help.
bye,
nxexo007
I resolved this situation without extend TextView class.
private ArrayList<TextWatcher> mEditTextWatcherList = new ArrayList<>();
private TextWatcher mTextWatcher1;
private TextWathcer mTextWatcher2;
mTextWathcer1 = 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) {}
};
mTextWathcer2 = 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) {}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
setListener(mTextWatcher1);
setListener(mTextWatcher2);
removeListeners();
}
private setListener(TextWatcher listener) {
mEditText.addTextChangedListener(listener);
mEditTextWatcherList.add(listener);
}
private removeListeners() {
for (TextWatcher t : mEditTextWatcherList)
mEditText.removeTextChangedListener(t);
mEditTextWatcherList.clear();
}
I struggled with a similar problem. I solved it by saving references to my textWatchers in an ArrayList:
private final List<TextWatcher> textWatchersForProfileNameTextBox = new ArrayList<>();
public void addTextWatcherToProfileNameTextBox(TextWatcher textWatcher){
textWatchersForProfileNameTextBox.add(textWatcher);
getProfileNameTextView().addTextChangedListener(textWatcher);
}
public void removeAllTextWatchersFromProfileNameTextView(){
while (!textWatchersForProfileNameTextBox.isEmpty())
getProfileNameTextView().removeTextChangedListener(textWatchersForProfileNameTextBox.remove(0));
}
If one, like me, deals with ViewHolder, then simply saving a reference to a text watcher upon its creation will not help. Upon reuse the view will get to some other ViewHolder which would not have a reference to that old text watcher, thus one won't be able to delete it.
Personally i chose to solve problem like #inazaruk, though updated code to Kotlin + renamed class to better reflect it's purpose.
class EditTextWithRemovableTextWatchers(context: Context?, attrs: AttributeSet?) : TextInputEditText(context, attrs) {
private val listeners by lazy { mutableListOf<TextWatcher>() }
override fun addTextChangedListener(watcher: TextWatcher) {
listeners.add(watcher)
super.addTextChangedListener(watcher)
}
override fun removeTextChangedListener(watcher: TextWatcher) {
listeners.remove(watcher)
super.removeTextChangedListener(watcher)
}
fun clearTextChangedListeners() {
for (watcher in listeners) super.removeTextChangedListener(watcher)
listeners.clear()
}
}
What I did to remove text watchers is very simple. I created an array to put my textwatchers:
final TextWatcher[] textWatchers = new TextWatcher[3];
I added them in:
final int CURRENT_PIN_CHECK = 0, NEW_PIN = 1, CONFIRM_PIN_CHECK = 2;
textWatchers[CURRENT_PIN_CHECK] = returnTextWatcherCheckPIN(CURRENT_PIN_CHECK);
textWatchers[NEW_PIN] = returnTextWatcherCheckPIN(NEW_PIN);
textWatchers[CONFIRM_PIN_CHECK] = returnTextWatcherCheckPIN(CONFIRM_PIN_CHECK);
My returnTextWatcherCheckPIN method instantiates a textWatcher with a different checker (switchMethod to check all four editTexts) on afterTextChanged.
Then whenever I remove a text watcher I just referenced the one from the array:
etPin4.removeTextChangedListener(textWatchers[CURRENT_PIN_CHECK]);
Check the listeners size of the editText on debug:
It's removed! That solved my problem!
I've run into the issue when using EditText in ViewHolder in RecyclerView item, and it was causing error of infinite loop, when ViewHolder was binding, cause the TextWatcher added in previous bind call was called, hence, never-ending loop..
The only working solution for that was to store TextWatcher's in the list, and then in onBindViewHolder, go trough that list and remove TextWatcher from the EditText.
private val textWatchers: MutableList<TextWatcher> = mutableListOf()
Add TextWatcher to list before assigning it to EditText:
textWatchers.add(textWatcher1)
vh.moneyAmount.editText?.addTextChangedListener(textWatcher1)
Remove them when binding the item, going to trough the entire textWatcherList:
private fun removeTextWatcher(vh: MoneyItemViewHolder) {
textWatchers.forEach { vh.moneyAmount.editText?.removeTextChangedListener(it) }
}
There isn't any other way to remove the TextWatcher's from EditText, than passing the TextWatcher object, hence it needs to be stored somewhere is we plan to remove it later.
Why not attach the TextWatcher reference to the EditText itself with setTag()?
if (etTagValue.getTag(R.id.textWatcherTag) != null) {
etTagValue.removeTextChangedListener((TextWatcher) etTagValue.getTag());
}
etTagValue.setText(myValue);
TextWatcher textWatcher = new DelayedTextWatcher(text -> meta.setDescription(text.toString()));
etTagValue.addTextChangedListener(textWatcher);
etTagValue.setTag(R.id.textWatcherTag, textWatcher);
In ids.xml under /values package:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="textWatcherTag" type="id" />
</resources>

Categories

Resources