简体   繁体   English

如何在android中实现搜索功能

[英]how to implement search function in android

hi i am new to android what i did is creating a list with strings and implementing the search using edit text,my code for this is as fallows嗨,我是 android 新手,我所做的是创建一个带有字符串的列表并使用编辑文本实现搜索,我的代码是休耕

 ((EditText)findViewById(R.id.EditText01)).setOnKeyListener(new OnKeyListener() 
    {

  public boolean onKey(View v, int keyCode, KeyEvent event)
  { String enteredText = ((EditText)findViewById(R.id.EditText01)).getText().toString();

      Iterator<String> strIt = strList.iterator();
    while(strIt.hasNext()){
      String str = strIt.next();

      if(str.startsWith(enteredText)){


       match.add(str);

     } 
     }

     } 

it works when focus is changed form edit text,but i need to work it like quick search box.when ever i enter a letter in edit text,the matching words will be displayed.how can i done this.pls post some code.Thank u in advance.当焦点从编辑文本中改变时它起作用,但我需要像快速搜索框一样工作。当我在编辑文本中输入一个字母时,将显示匹配的单词。我该怎么做。请发布一些代码。谢谢你提前。

Try implementing TextWatcher interface.尝试实现 TextWatcher 接口。

It has three methods which you need to override.它具有三个您需要覆盖的方法。

public void afterTextChanged(Editable s) {
        
        Log.v("afterTextChanged","here");
    }
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        
        Log.v("beforeTextChanged","here");
    }
    
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

I think this will do your work.我认为这会完成你的工作。

Take a Look at AutoCompleteTextView.看看 AutoCompleteTextView。

Basically you can create an ArrayAdapter or a SimpleAdapter that contains your Strings.基本上,您可以创建一个包含字符串的 ArrayAdapter 或 SimpleAdapter。 Then just replace your EditText with the AutoCompleteTextView and automagically ... you get the typeahead behavior that you describe.然后只需将您的 EditText 替换为 AutoCompleteTextView 并自动...您将获得您描述的预输入行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM