Android搜索自动提示功能 AutocompleteTextView

Android搜索自动提示功能 AutocompleteTextView

Android搜索自动提示功能 AutocompleteTextView

 

 

1.配置main.xml中自动提示控件:

<AutoCompleteTextView
            android:id="@+id/autotv_searchresult"
            android:layout_width="280dip"
            android:layout_height="35dip"
            android:layout_centerInParent="true"
            android:background="#00000000"
            android:completionThreshold="1"
            android:imeOptions="actionSearch"
            android:dropDownHeight="wrap_content"
            android:dropDownVerticalOffset="10dip"
            android:hint="搜索歌曲,歌手,音乐盒名..."
            android:singleLine="true" />

 

 

注:android:dropDownVerticalOffset="10dip"是可以将提示的信息与边框开一段距离的属性,通常都会用的到

 

2.建立搜索栏的布局.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/brandName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/searchText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="gone" />

</LinearLayout>

 

 

注: android:visibility="gone"这个是加入输入英文字母有中文提示的关键性代码

 

 

3.定义2个数组并在程序的开始给数组赋值:

// 所有搜索的信息
 public static ArrayList<HashMap<String, String>> list_searchAll = new ArrayList<HashMap<String, String>>();
 // 一些搜索的信息
 public static ArrayList<HashMap<String, String>> list_searchSome = new ArrayList<HashMap<String, String>>();

 

private void addAllSearch(String input, String output)
 {
  HashMap<String, String> item;
  item = new HashMap<String, String>();
  item.put("brandSearchText", input);
  item.put("brandName", output);
  list_searchAll.add(item);
 }

 private void addAllSearchItems()
 {
  addAllSearch("XBH xuebuhui xbh", "学不会");
  addAllSearch("YXJ yixiangji yxj", "异想记");
  addAllSearch("XWZ xiaowangzi wangzi", "小王子的漂流瓶");
  addAllSearch("XYGZJ xiayige xygzj", "下一个自己");
  addAllSearch("NYFZ nuoyafanzhou nyfz", "诺亚方舟");
  addAllSearch("XT xintiao xt", "心跳");
  addAllSearch("QS qinshang qs", "琴伤");
  addAllSearch("AQSFYR aiqinshifou aqsf", "爱情是否依然");
  addAllSearch("NZFRSM nizaifanrao nzfrsm", "你在烦扰什么");
  addAllSearch("WMHGHD womenghuigenghaode wmhgh", "我们会更好的");

 }

 private void addSomeSearch(String input, String output)
 {
  HashMap<String, String> item;
  item = new HashMap<String, String>();
  item.put("brandSearchText", input);
  item.put("brandName", output);
  list_searchSome.add(item);
 }

 private void addSomeSearchItems()
 {
  // A
  addSomeSearch("AQMM aiqingmaima", "爱情买卖");
  addSomeSearch("AWNJBBW aiwonijiubbw", "爱我你就抱抱我");
  addSomeSearch("ABZJFFS aibuzaijiuffs", "爱不在就放放手");
  // B
  addSomeSearch("BCYS banchengyansha", "半城烟沙");
  addSomeSearch("BFSDLA bufengshoudelianai", "不分手的恋爱");
  addSomeSearch("BYGSMM buyaogaoshumama", "不要告诉妈妈");
  }

 

 

 

 

4.得到控件id,创建SimpleAdapter适配器:

private AutoCompleteTextView autotv_search;
private SimpleAdapter mAdapter;

 

autotv_search = (AutoCompleteTextView) findViewById(R.id.autotv_search);

 

注:适配器的实例化可以在监听中

 

5.设置AutoCompleteTextView的监听

private void autoSearchListen()
 {
  autotv_search.setOnKeyListener(new View.OnKeyListener()
  {
   // 添加软键盘事件(让软键盘有一个搜索的图标)
   @Override
   public boolean onKey(View v, int keyCode, KeyEvent event)
   {
    // TODO Auto-generated method stub
    if (keyCode == KeyEvent.KEYCODE_ENTER)
    {
     if (event.getAction() == KeyEvent.ACTION_UP)
     {
      InputMethodManager imm = (InputMethodManager) v
        .getContext().getSystemService(
          Context.INPUT_METHOD_SERVICE);
      if (imm.isActive())
      {
       imm.hideSoftInputFromWindow(v
         .getApplicationWindowToken(), 0);
      }
      return true;
     }

    }
    return false;
   }
  });

注:if (keyCode == KeyEvent.KEYCODE_ENTER)
    {
     if (event.getAction() == KeyEvent.ACTION_UP)
     {
   是当回车键起来的时候才触发不然会被调用2次,一次按下一次弹起
  
  autotv_search.setOnClickListener(new OnClickListener()
  {

   @Override
   public void onClick(View v)
   {
    // TODO Auto-generated method stub
    if (autotv_search.getText().toString().equals(""))
    {
     mAdapter = new SimpleAdapter(SearchActivity.this,
       HomeActivity.list_searchAll, R.layout.searchlist, new String[] {
         "brandSearchText", "brandName" },
       new int[] { R.id.tv_searchText, R.id.tv_brandName });
     autotv_search.setAdapter(mAdapter);
     autotv_search.showDropDown();
    }
   }
  });

 

注:点击搜索框触发,记得参数都要一一对应,你懂的...

autotv_search.showDropDown();手动弹出提示

  
  autotv_search.setOnFocusChangeListener(new OnFocusChangeListener()
  {

   @Override
   public void onFocusChange(View v, boolean hasFocus)
   {
    if (hasFocus & autotv_search.getText().toString().equals(""))
    {
     mAdapter = new SimpleAdapter(SearchActivity.this,
       HomeActivity.list_searchAll, R.layout.searchlist, new String[] {
         "brandSearchText", "brandName" },
       new int[] { R.id.tv_searchText, R.id.tv_brandName });
     autotv_search.setAdapter(mAdapter);
     autotv_search.showDropDown();
    }
   }
  });
  
  // 点击条目的监听
  autotv_search.setOnItemClickListener(new OnItemClickListener()
  {

   @Override
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id)
   {
    TextView tv =  (TextView) view.findViewById(R.id.tv_brandName);
    autotv_search.setText(tv.getText().toString());
    autotv_search.setSelection(autotv_search.getText().toString().length());
   }
  });
  
//TextWatcher 是本应用的关键地方...这里感谢云童鞋给的提示,当字符产生变换的时候就调用

 

  TextWatcher tw = new TextWatcher()
  {
   
   @Override
   public void onTextChanged(CharSequence s, int start, int before, int count)
   {
    // TODO Auto-generated method stub
    if (autotv_search.getText().toString().equals(""))
    {
     mAdapter = new SimpleAdapter(SearchActivity.this,
       HomeActivity.list_searchAll, R.layout.searchlist, new String[] {
         "brandSearchText", "brandName" },
       new int[] { R.id.tv_searchText, R.id.tv_brandName });
     autotv_search.setAdapter(mAdapter);
     autotv_search.showDropDown();
    } else if (autotv_search.getText().toString().length() < 3)
    {
     mAdapter = new SimpleAdapter(SearchActivity.this,
       HomeActivity.list_searchSome, R.layout.searchlist, new String[] {
         "brandSearchText", "brandName" },
       new int[] { R.id.tv_searchText, R.id.tv_brandName });
     autotv_search.setAdapter(mAdapter);
     // mAdapter.notifyDataSetChanged();
    }
   }
   
   @Override
   public void beforeTextChanged(CharSequence s, int start, int count,
     int after)
   {
    // TODO Auto-generated method stub
    
   }
   
   @Override
   public void afterTextChanged(Editable s)
   {
    // TODO Auto-generated method stub
    if (autotv_search.getText().toString().equals(""))
    {
     mAdapter = new SimpleAdapter(SearchActivity.this,
       HomeActivity.list_searchAll, R.layout.searchlist, new String[] {
         "brandSearchText", "brandName" },
       new int[] { R.id.tv_searchText, R.id.tv_brandName });
     autotv_search.setAdapter(mAdapter);
     autotv_search.showDropDown();
    }
   }
  };
  // 添加文字改变的监听
  autotv_search.addTextChangedListener(tw);
  
 }

 

结束语:这样一直改变适配器的方法不知道会不会在性能上产生一定的问题...在真机上测试还是很快速的,程序还有很多要优化的地方,如果有更好的方法的还望指点呀...

Android搜索自动提示功能 AutocompleteTextView,布布扣,bubuko.com

Android搜索自动提示功能 AutocompleteTextView

上一篇:转载:Delphi中类的运行期TypeInfo信息结构说明


下一篇:VMware Windows Server 2008 R2 X64 虚拟机安装教程