自定义适配器中EditText的文本更改侦听器

时间:2017-01-10 13:26:49

标签: android listview textwatcher

在我的Android应用中,我有EditTexts的listview。更改EditText值后,我将ArrayList中的新值存储在afterTextChanged中。但是,在仅编辑一个字段后ArrayList获取具有相同编辑字符串的多个项目时,出现错误的原因。如何让ArrayList仅为每个字段获取一次编辑后的字符串?

class MyListViewAdapter extends ArrayAdapter<KeyValueList>
{
private int layoutResource;

MyListViewAdapter(Context context, int layoutResource, List<KeyValueList> keyValueList)
{
    super(context, layoutResource, keyValueList);
    this.layoutResource = layoutResource;
}

@Override
public View getView(final int position, final View convertView, @NonNull ViewGroup parent)
{
    View view = convertView;
    if (view == null)
    {
        LayoutInflater layoutInflater = LayoutInflater.from(getContext());
        view = layoutInflater.inflate(layoutResource, null);
    }

    final KeyValueList keyValuelist = getItem(position);

    if (keyValuelist != null)
    {
        TextView key = (TextView) view.findViewById(R.id.key);
        EditText value = (EditText) view.findViewById(R.id.value);
        ImageView image = (ImageView) view.findViewById(R.id.img);

        value.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)
            {
                HashMap<String, String> edit = new HashMap<>();

                edit.put("string", s.toString());

                openEntry.edit_list.add(edit);
            }
        });
....
}

2 个答案:

答案 0 :(得分:1)

我也面临类似问题,将EditText设为final并检查条件hasFocus()

final EditText value = (EditText) view.findViewById(R.id.value);
...
@Override
public void afterTextChanged(Editable s)
{

   if(value.hasFocus()){
        HashMap<String, String> edit = new HashMap<>();
        edit.put("string", s.toString());
        openEntry.edit_list.add(edit);
   }

}

这可能会帮助一个有同样问题的人

答案 1 :(得分:0)

如果您使用 set TextChangedListener(如果存在),或者在添加新文件之前从视图中删除所有TextChangedListener,它可能会有效。

这些视图已被回收,但您一直在向他们添加新的侦听器。我认为这可能是问题所在。