安卓:addTextChangedListener 运行不正常

标签 android android-edittext

我想对用户在 EditText 中键入内容使用react,所以我使用了 addTextChangedListener 方法。 当用户键入单个字符时,onTextChanged 代码正在运行,一切正常。 因此,例如,如果用户键入“a”,则 onTextChanged 将开始运行

但是如果用户键入另一个字符,例如 b ,则不会调用 onTextChanged。

(EditText中的文本现在应该是“ab”)

代码:

  et = (EditText)findViewById(R.id.edittextsearch);
  et.addTextChangedListener(new TextWatcher() 
  {

      public void afterTextChanged(Editable s){}
      public void beforeTextChanged(CharSequence s, int start, int count,int after){}
      public void onTextChanged(CharSequence s, int start, int before,int count)
      {
          int i = 0;
          textlength=et.getText().length();
          arr_sort.clear();
          for(i=0;i<3;i++)
          {
              if(textlength<=your_array_contents[i].length())
              {
                  if(et.getText().toString().equalsIgnoreCase((String) your_array_contents[i].subSequence(0, textlength)))
                  {
                      arr_sort.add(your_array_contents[i]); 
                  }
              }
          }
          lv.setAdapter(new ArrayAdapter<String>(GroupsActivity.this,
                    android.R.layout.simple_list_item_multiple_choice, arr_sort)); 
      }

  });

感谢您的帮助!

最佳答案

从你的代码中,我能理解的是,你想要过滤 ListView

与其自己进行过滤,不如使用 listView.setFilterText(String)

像这样:

第一次添加您的适配器。

lv.setAdapter(new ArrayAdapter<String>(GroupsActivity.this,
                    android.R.layout.simple_list_item_multiple_choice, your_array_contents));

然后添加TextWatcher:

txtFilter.addTextChangedListener(new TextWatcher() {
    public void afterTextChanged(Editable s) {
        if(s.length()==0){
            lv.clearTextFilter();
        }
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after){
    }
    public void onTextChanged(CharSequence s, int start, int before, int count)
    {
        lv.setTextFilterEnabled(true);
        lv.setFilterText(s.toString());
    }
});

关于安卓:addTextChangedListener 运行不正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7995146/

相关文章:

android - rxjava 与每个循环

java - EditText 输入金额

Android-将日期和文本保存到手机内存中的 SQLite?

java - AddTextChangedListener 到循环生成的 EditText View

java - 在 XML 或 java 文件中编写相同的代码(用于布局)之间是否存在性能差异?

java - 将所有 recyclerview 项目从 Activity1 传递到 Activity2 recyclerview 项目

android - Android中对话框内具有固定高度的ScrollView

android - 如何在Android应用程序中一起播放视频和音频

Android 如何使 EditText 在 ListView 中可编辑

android - 在拖动时选择编辑文本中的一些文本