Related
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>
I have code like this
#Override
public void onCreate(Bundle savedInstanceState) {
addItemsOnSpinnerOrgaLevel();
btn_getReport.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//How can i access map and list defined in orgaLevelTask(AsyncTask)???
Like
String option = parent.getItemAtPosition(pos).toString();
int orgaCode = orgaLevelMap.get(option);
// Both are defined in AsyncTask ??
}); //end of anonymous class
} //end of onCreate()
public void addItemsOnSpinnerOrgaLevel() {
orgaLevelTask = new OrgaLevelTask(AccountReportActivity.this, spinner_orgaLevel, spinner_branch, txt_extra, txt_extra1);
orgaLevelTask.execute();
} //end of addItemsOnSpinnerOrgaLevel()
In AsyncTask onPostExecute() Method i have
#Override
protected void onPostExecute(ArrayList<OrgaLevel> result) {
super.onPostExecute(result);
if (result != null) {
addItemsOnSpinnerOrgaLevel(result);
}
dialog.dismiss();
} //end of onPostExecute()
public void addItemsOnSpinnerOrgaLevel(ArrayList<OrgaLevel> result) {
orgaLevelElementslist = new ArrayList<String>();
orgaLevelElementslist.add("All");
orgaLevelMap = new HashMap<String, Integer>();
orgaLevelMap.put("All", 0);
for (int i=0; i<result.size(); i++) {
OrgaLevel orgaLevelRecord = (OrgaLevel) result.get(i);
String key = orgaLevelRecord.getOrgaName();
String value = orgaLevelRecord.getOrgaCode();
orgaLevelMap.put(key, Integer.parseInt(value));
orgaLevelElementslist.add(key);
} //end of for()
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(accountReportActivity, android.R.layout.simple_spinner_item, orgaLevelElementslist);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_orgaLevel.setAdapter(dataAdapter);
setSpinnerOrgaLevelListener();
} //end of addItemsOnSpinnerOrgaLevel()
private void setSpinnerOrgaLevelListener() {
spinner_orgaLevel.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
String option = parent.getItemAtPosition(pos).toString();
int orgaCode = orgaLevelMap.get(option);
subOrgaLevelTask = new SubOrgaLevelTask(accountReportActivity, spinner_branch, orgaCode);
subOrgaLevelTask.execute();
} //end of onItemSelected()
}); //end of anonymous class
} //end of setSpinnerOrgaLevelListener()
In the subOrgaLevelTask i also have the same hash map as in this class. You can see that what i am trying to do is, put a key value in spinner. So when my btn_getReport button get click then i get the value of the selected item. Like if All is slected then i get 0 and so on. This key value thing is working. The problem is when btn_getReport get click then how can i get the value of the selected item. Because i am filling items in a background thread(In OrgaLevelTask and SubOrgaLevelTask) and my button is in Activity. So how can i do that when button get click, then i get the values from the map defined in OrgaLevelTask and SubOrgaLevelTask ?
Thanks
well, make them public in orgaLevelTask, and simply access them. orgaLevelTask should be a variable in you activity class. Have you tried it? any errors?
You must make sure orgaLevelTask members will be accessed in thread safe manner
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>
How do you get the current top suggestion in an AutoCompleteTextView? I have it suggesting items, and I have a text change listener registered. I also have a list on the same screen. As they type, I want to scroll the list to the current "best" suggestion. But I can't figure out how to access the current suggestions, or at least the top suggestion. I guess I'm looking for something like AutoCompleteTextView.getCurrentSuggestions():
autoCompleteTextView.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
String currentText = autoCompleteTextView.getText();
String bestGuess = autoCompleteTextView.getCurrentSuggestions()[0];
// ^^^ mewthod doesn't exist
doSomethingWithGuess(bestGuess);
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// do nothing
}
public void afterTextChanged(Editable s) {
// do nothing
}
});
I've done what you want to do with the following code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.autocomplete_1);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, COUNTRIES);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit);
textView.setAdapter(adapter);
adapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
Log.d(TAG, "dataset changed");
Object item = adapter.getItem(0);
Log.d(TAG, "item.toString "+ item.toString());
}
});
}
item.toString will print the text that is displayed on the first item.
Note that this will happen even if you aren't showing the pop-up (suggestions) yet. Also, you should check if there are any items that passed the filter criteria (aka the user's input).
To solve the first problem:
int dropDownAnchor = textView.getDropDownAnchor();
if(dropDownAnchor==0) {
Log.d(TAG, "drop down id = 0"); // popup is not displayed
return;
}
//do stuff
To solve the second problem, use getCount > 0
AutoCompleteTextView does not scroll down to the best selection, but narrows down the selection as you type. Here is an example of it: http://developer.android.com/resources/tutorials/views/hello-autocomplete.html
As I see it from AutoCompleteTextView there is no way to get current list of suggestions.
The only way seem to be writing custom version of ArrayAdapter and pass it to AutoCompleteTextView.setAdapter(..). Here is the source to ArrayAdapter. You must only change a method in inner class ArrayFilter.performFiltering() so that it exposes FilterResults:
.. add field to inner class ArrayFilter:
public ArrayList<T> lastResults; //add this line
.. before end of method performFiltering:
lastResults = (ArrayList<T>) results; // add this line
return results;
}
Using it like this (adapted example from link):
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
CustomArrayAdapter<String> adapter = new CustomArrayAdapter<String>(this, R.layout.list_item, COUNTRIES);
textView.setAdapter(adapter);
// read suggestions
ArrayList<String> suggestions = adapter.getFilter().lastResult;
I have an ArrayAdapter (myAdapter) attached to an AutoCompleteTextView (textView) component.
Once the user presses a character I would like to populate AutoCompleteTextView's drop down list with items containing this character.
I retrieve the items using AsyncTask (which uses a web service).
I call myAdapter.add(item) but the drop down list is empty.
I added a call myAdapter.getCount() after each addition and it shows zero every time.
Calling notifyDataSetChanged() didn't help.
I even tried to add simple String objects instead of my custom objects, to no avail.
What am I doing wrong?
Edit: I changed the code as miette suggested below but still to no avail.
Generally, what I do is after text is changed in my auto complete text view, I call a new AsyncTask and pass it the entered text and a Handler (see afterTextChanged()). The task retrieves objects relevant to the text and once done the Handler's handleMessage() is called. In handleMessage() I attempt to populate the adapter's objects. But still the adapter's drop down list ends up empty.
Here is my code:
public class AddStockView extends Activity
implements OnClickListener, OnItemClickListener, TextWatcher {
ArrayAdapter<Stock> adapter;
AutoCompleteTextView textView;
Vector<Stock> stocks;
public AddStockView() {
// TODO Auto-generated constructor stub
stocks = new Vector<Stock>();
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.add_stock_view);
findViewById(R.id.abort_button).setOnClickListener(this);
adapter = new ArrayAdapter<Stock>(this,
android.R.layout.simple_dropdown_item_1line, stocks);
//adapter.setNotifyOnChange(true);
textView = (AutoCompleteTextView)
findViewById(R.id.search_edit_text);
textView.setAdapter(adapter);
textView.setOnItemClickListener(this);
textView.addTextChangedListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId())
{
case R.id.abort_button:
finish();
break;
case R.id.search_edit_text:
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// TODO Auto-generated method stub
Stock stockToAdd = (Stock)parent.getAdapter().getItem(position);
//TODO: Add the above stock to user's stocks and close this screen
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.layout.menu, menu);
CategoryMenu.getInstance().populateMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
CategoryMenu.getInstance().menuItemSelected(item, this);
return false;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return true;
}
#Override
public void afterTextChanged(Editable text) {
// TODO Auto-generated method stub
if (text.toString().equals(""))
return;
new AppTask().execute(new AppTask.Payload(Consts.taskType.SEARCH_STOCK,
new Object[] {text, handler}, this));
}
#Override
public void beforeTextChanged(CharSequence a0, int a1, int a2, int a3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence a0, int a1, int a2, int a3) {
// TODO Auto-generated method stub
}
private void addStockItemsToAdapter(Vector<Object> dataItems)
{
for (int i = 0; i <dataItems.size(); i++)
{
Stock stk = (Stock)dataItems.elementAt(i);
stocks.add(stk);
}
}
public void populateAdapter()
{
addStockItemsToAdapter(ContentReader.getInstance.getDataItems());
adapter.notifyDataSetChanged();
int size = adapter.getCount(); // size == 0 STILL!!!!
textView.showDropDown();
}
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
populateAdapter();
}
};
}
Thanks a lot, Rob
I had the exact same problem. After examining the ArrayAdapter and AutoCompleteTextView source code, I found out that the problem was, in short, that:
the original object list is stored in ArrayAdapter.mObjects.
However, AutoCompleteTextView enables ArrayAdapter's filtering, meaning that new objects are added to ArrayAdapter.mOriginalValues, while mObjects contains the filtered objects.
ArrayAdapter.getCount() always returns the size of mObjects.
My solution was to override ArrayAdapter.getFilter() to return a non-filtering filter. This way mOriginalValues is null and mObjects is used instead in all cases.
Sample code:
public class MyAdapter extends ArrayAdapter<String> {
NoFilter noFilter;
/*
...
*/
/**
* Override ArrayAdapter.getFilter() to return our own filtering.
*/
public Filter getFilter() {
if (noFilter == null) {
noFilter = new NoFilter();
}
return noFilter;
}
/**
* Class which does not perform any filtering.
* Filtering is already done by the web service when asking for the list,
* so there is no need to do any more as well.
* This way, ArrayAdapter.mOriginalValues is not used when calling e.g.
* ArrayAdapter.add(), but instead ArrayAdapter.mObjects is updated directly
* and methods like getCount() return the expected result.
*/
private class NoFilter extends Filter {
protected FilterResults performFiltering(CharSequence prefix) {
return new FilterResults();
}
protected void publishResults(CharSequence constraint,
FilterResults results) {
// Do nothing
}
}
}
Create an array adapter with a vector or array like:
ArrayAdapter(Context context, int textViewResourceId, T[] objects)
By initializing your arrayadapter, you will make it listen to objects array. Do not add item to the adapter or clear the adapter, do your additions in "objects" array and also clear it. After changes on this array call
adapter.notifyDataSetChanged();
More specifically
ArrayAdapter<YourContentType> yourAdapter = new ArrayAdapter<YourContentType> (this,R.id.OneOfYourTextViews,YourDataList);
yourAdapter.notifyDataSetChanged();
aTextView.setText(yourAdapter.isEmpty() ? "List is empty" : "I have too many objects:)");
This should be done after loading YourDataList, I checked your code, are you sure handler calls addStockItemsToAdapter() before you look your adapter is empty or not?
You should also check if stocks vector has any elements in it.
Where do you call addItemsToAdapter()?
Can you show us, how you have tried to add simple Strings to your Adapter?
Edit: out of the comments the helpful code sample:
adapter = new ArrayAdapter<Stock>(this, android.R.layout.simple_dropdown_item_1line, stocks);
adapter.notifyDataSetChanged();
textView.setAdapter(adapter);