AutoCompleteTextView按照关键字从服务器上获得数据显示下拉列表

来源:互联网 发布:编程人生 pdf 编辑:程序博客网 时间:2024/06/06 14:16

        最近项目原因,需要做出一个类似baidu搜索时下拉框的效果如图

        于是乎想了多种办法,一种是利用AutoCompleteTextView+ListView方式,但是这种方式有一个缺点就是需要用帧布局,同时在利用AutoCompleteTextView.addTextChangedListener方法控制ListView的显示和消失时遇到一个很大的问题就是无法让其消失,即使你选中了一个条目,因为TextChanged的原因,ListView也是以一条你选中的条目为显示内容的形式在AutoCompleteTextView的下方,没有找到好的解决办法。

        之所以想到以上这种办法的原因是在项目的一开始没有使用AutoCompleteTextView的原生态的下拉列表(有各种各样的不更新造成的),后来在使用AutoCompleteTextView+ListView无效的情况下只能回到AutoCompleteTextView的原生态的下拉列表的方法上。

        http://stackoverflow.com/tags/autocompletetextview/hot这是stackoverflow上关于AutoCompleteTextView的FAQ,从中我们可以看到有多个关于从网上获取条目然后显示在AutoCompleteTextView的列表之上的问题和相应的回答。最终选中了http://stackoverflow.com/questions/8653260/autocomplete-in-android-not-working-with-dynamic-data这个问题当中名为iNan的解答,并对其进行了改进。

        具体代码如下

WikiSuggestActivity 

import org.apache.http.client.HttpClient;import org.apache.http.client.ResponseHandler;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.BasicResponseHandler;import org.apache.http.impl.client.DefaultHttpClient;import org.json.JSONArray;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.util.Log;import android.widget.ArrayAdapter;import android.widget.AutoCompleteTextView;/** * @Title: WikiSuggestActivity.java * @Package com.yang.testautocompletetextview * @Description: 参考http://stackoverflow.com/questions/8653260/autocomplete-in-android-not-working-with-dynamic-data * @author Yang   * @date 2012-8-12 下午2:59:54 * @version V1.0 */public class WikiSuggestActivity extends Activity {public String data;    public List<String> suggest;    public AutoCompleteTextView autoComplete;    public ArrayAdapter<String> aAdapter;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        suggest = new ArrayList<String>();        autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);        autoComplete.addTextChangedListener(new TextWatcher(){            public void afterTextChanged(Editable editable) {            }            public void beforeTextChanged(CharSequence s, int start, int count, int after) {            }            public void onTextChanged(CharSequence s, int start, int before, int count) {                String newText = s.toString();                new getJson().execute(newText);            }        });    }   class getJson extends AsyncTask<String,String,String>{    @Overrideprotected void onPostExecute(String result) {super.onPostExecute(result); aAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,suggest);         autoComplete.setAdapter(aAdapter);         aAdapter.notifyDataSetChanged();}@Override    protected String doInBackground(String... key) {        String newText = key[0];        newText = newText.trim();        newText = newText.replace(" ", "+");        try{            HttpClient hClient = new DefaultHttpClient();            HttpGet hGet = new HttpGet("http://en.wikipedia.org/w/api.php?action=opensearch&search="+newText+"&limit=8&namespace=0&format=json");            ResponseHandler<String> rHandler = new BasicResponseHandler();            data = hClient.execute(hGet,rHandler);            suggest = new ArrayList<String>();            JSONArray jArray = new JSONArray(data);            for(int i=0;i<jArray.getJSONArray(1).length();i++){            String SuggestKey = jArray.getJSONArray(1).getString(i);            suggest.add(SuggestKey);            }        }catch(Exception e){            Log.w("Error", e.getMessage());        }        return null;    }   }}
activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent" >    <AutoCompleteTextView        android:id="@+id/autoCompleteTextView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_centerVertical="true"        android:ems="10" />    <!-- android:ems  设置TextView的宽度为N个字符的宽度。这里测试为一个汉字字符宽度 --></RelativeLayout>
item.xml

<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="wrap_content" android:layout_height="wrap_content"  android:id="@+id/online_user_list_item_textview" ></TextView>
效果图如下:



整个项目代码下载地址