Android AutoCompleteTextView不显示下拉列表

Android AutoCompleteTextView不显示下拉列表,android,android-widget,autocompletetextview,Android,Android Widget,Autocompletetextview,我有一个按钮(setButton),按下按钮后,我希望修改后的AutoCompleteTextView立即显示下拉菜单 我有两节课 AutoCompleteTextViewTest1Activity.class package com.autocompletetextviewtest1; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.Vie

我有一个按钮(setButton),按下按钮后,我希望修改后的AutoCompleteTextView立即显示下拉菜单

我有两节课

AutoCompleteTextViewTest1Activity.class

package com.autocompletetextviewtest1;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;


public class AutoCompleteTextViewTest1Activity extends Activity {
ArrayAdapter<String> adapter1;
ArrayAdapter<String> adapter2;
private InstantAutoComplete actv;
private String[] countries2 ={"Taiwan", "China", "S. Korea", "USA", "Japan", "Russia"};
private String[] countries={};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, countries);
adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, countries2);
actv = (InstantAutoComplete)findViewById(R.id.actv);
actv.setAdapter(adapter1);

Button setButton = (Button)findViewById(R.id.setButton);
Button clearButton = (Button)findViewById(R.id.clearButton);

setButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
actv.setAdapter(adapter2);
actv.requestFocus();
}
});

clearButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
actv.setAdapter(adapter1);
        }
});
}
}

但我的AutoCompleteTextView在按下设置按钮时不会显示下拉菜单。我能做什么?谢谢

尝试调用setButton onClick中的actv.invalidate(),以使用新更新的适配器刷新视图。

这对我来说很有效。请注意,我在适当的位置有日志来检查我的webservice调用是否正确,以及它的返回值。这对于自动完成的工作至关重要。在您的情况下,您可能需要删除webservice调用并使用硬编码的值填充适配器

在onCreate中初始化

fromAutoComplete = new AutoComplete(this, R.layout.autocomplete_list_item);
fromAutoComplete.setNotifyOnChange(true);
fromAddress = (AutoCompleteTextView) findViewById(R.id.fromAddress);
fromAddress.setAdapter(fromAutoComplete);
fromAddress.setOnItemClickListener(this);
自动完成适配器,用于检查字符并反复调用Web服务,以显示在下拉列表中

请注意

  • 这个api需要一个google api密钥,您需要自己生成该密钥。另外,不要忘记为您的密钥启用位置API。没有这个,它就不能工作
  • 在webservice调用中放置变量很重要(出于某些疯狂的原因)。最后的传感器变量对我有效。您可以在您的logcat上的fiddler或chrome上测试它
  • public自动完成(上下文,int textViewResourceId){
    super(上下文,textViewResourceId);
    }
    @凌驾
    public int getCount(){
    返回resultList.size();
    }
    @凌驾
    公共字符串getItem(int索引){
    返回resultList.get(索引);
    }
    @凌驾
    公共过滤器getFilter(){
    过滤器过滤器=新过滤器(){
    @凌驾
    受保护的筛选器结果性能筛选(CharSequence约束){
    FilterResults FilterResults=新的FilterResults();
    if(约束!=null){
    //检索自动完成结果。
    结果列表=自动完成(constraint.toString());
    //将数据分配给FilterResults
    filterResults.values=结果列表;
    filterResults.count=resultList.size();
    }
    返回过滤器结果;
    }
    @凌驾
    受保护的void publishResults(CharSequence约束、FilterResults结果){
    if(results!=null&&results.count>0){
    notifyDataSetChanged();
    }否则{
    notifyDataSetionValidated();
    }
    }
    };
    回流过滤器;
    }
    专用ArrayList自动完成(字符串输入){
    ArrayList resultList=null;
    HttpURLConnection conn=null;
    StringBuilder jsonResults=新建StringBuilder();
    试一试{
    StringBuilder sb=新的StringBuilder(PLACES\u API\u BASE+TYPE\u AUTOCOMPLETE+OUT\u JSON);
    sb.追加(“?key=“+API_key+”&sensor=false”);
    sb.追加(“&components=国家:in”);
    sb.append(“&input=“+urlcoder.encode”(输入,“utf8”));
    d(Log_标记,“调用”+sb.toString());
    URL=新URL(sb.toString());
    conn=(HttpURLConnection)url.openConnection();
    InputStreamReader in=新的InputStreamReader(conn.getInputStream());
    //将结果加载到StringBuilder中
    int-read;
    char[]buff=新字符[1024];
    while((read=in.read(buff))!=-1){
    附加(buff,0,read);
    }
    }捕获(格式错误){
    e(Log_标记,“错误处理位置API URL”,e);
    返回结果列表;
    }捕获(IOE异常){
    Log.e(Log_标签,“连接到位置API时出错”,e);
    返回结果列表;
    }最后{
    如果(conn!=null){
    连接断开();
    }
    }
    试一试{
    //根据结果创建JSON对象层次结构
    JSONObject jsonObj=新的JSONObject(jsonResults.toString());
    JSONArray predsjssonarray=jsonObj.getJSONArray(“预测”);
    //从结果中提取位置描述
    resultList=新的ArrayList(predsjSonaray.length());
    对于(int i=0;i
    从下拉文本中选择项目时

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        Double latitude, longitude;
        ArrayList<String> resultList = null;
        HttpURLConnection conn = null;
        StringBuilder jsonResults = new StringBuilder();
        String str = (String) adapterView.getItemAtPosition(position);
        try {
            StringBuilder sb = new StringBuilder(
                    "http://maps.googleapis.com/maps/api/geocode/json?" + "address="
                            + URLEncoder.encode(str, "utf-8") + "&sensor=true");
    
            URL url = new URL(sb.toString());
            Log.d("Taxeeta", url.toString() + " Called");
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
    
            // Load the results into a StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                jsonResults.append(buff, 0, read);
            }
        } catch (MalformedURLException e) {
            Log.e("Taxeeta", "Error processing Places API URL", e);
        } catch (IOException e) {
            Log.e("Taxeeta", "Error connecting to Places API", e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    
        try {
            // Create a JSON object hierarchy from the results
            JSONObject jsonObj = new JSONObject(jsonResults.toString());
            JSONObject location = ((JSONObject) jsonObj.getJSONArray("results").get(0))
                    .getJSONObject("geometry").getJSONObject("location");
            latitude = location.optDouble("lat");
            longitude = location.optDouble("lng");
            Log.d("Taxeeta", "Received Latitude " + latitude + ": Longitude" + longitude);
            if (view.getId() == fromAddress.getId()) {
                source = new GeoPoint((int) (latitude * 1E6), (int) (longitude * 1E6));
                Log.d("Taxeeta", "Source Done");
            } else {
                destination = new GeoPoint((int) (latitude * 1E6), (int) (longitude * 1E6));
                Log.d("Taxeeta", "Destination Done");
            }
        } catch (JSONException e) {
            Log.e("Taxeeta", "Cannot process JSON results", e);
        }
    }
    
    @覆盖
    public void onItemClick(AdapterView AdapterView,视图视图,整型位置,长id){
    双纬度,经度;
    ArrayList resultList=null;
    HttpURLConnection conn=null;
    StringBuilder jsonResults=新建StringBuilder();
    String str=(字符串)adapterView.getItemAtPosition(位置);
    试一试{
    StringBuilder sb=新的StringBuilder(
    "http://maps.googleapis.com/maps/api/geocode/json?“+”地址=”
    +编码(str,“utf-8”)+“&sensor=true”);
    URL=新URL(sb.toString());
    Log.d(“taxeta”,url.toString()+“调用”);
    conn=(HttpURLConnection)url.openConnection();
    InputStreamReader in=新的InputStreamReader(conn.getInputStream());
    //将结果加载到StringBuilder中
    int-read;
    char[]buff=新字符[1024];
    while((read=in.read(buff))!=-1){
    附加(buff,0,read);
    }
    }捕获(格式错误){
    Log.e(“taxeta”,“错误处理地点API URL”,e);
    }捕获(IOE异常){
    Log.e(“taxeta”,“连接到地方API时出错”,e);
    }最后{
    如果(conn!=null){
    连接断开();
    }
    }
    试一试{
    //根据结果创建JSON对象层次结构
    JSONObject jsonObj=新的JSONObject(jsonResults.toString());
    JSONObject位置=((JSONObject)JSONObject.getJSONArray(“结果”).get(0))
    
    public AutoComplete(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }
    
    @Override
    public int getCount() {
        return resultList.size();
    }
    
    @Override
    public String getItem(int index) {
        return resultList.get(index);
    }
    
    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                if (constraint != null) {
                    // Retrieve the autocomplete results.
                    resultList = autocomplete(constraint.toString());
    
                    // Assign the data to the FilterResults
                    filterResults.values = resultList;
                    filterResults.count = resultList.size();
                }
                return filterResults;
            }
    
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null && results.count > 0) {
                    notifyDataSetChanged();
                } else {
                    notifyDataSetInvalidated();
                }
            }
        };
        return filter;
    }
    
    private ArrayList<String> autocomplete(String input) {
        ArrayList<String> resultList = null;
    
        HttpURLConnection conn = null;
        StringBuilder jsonResults = new StringBuilder();
        try {
            StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
            sb.append("?key=" + API_KEY+"&sensor=false");
            sb.append("&components=country:in");
            sb.append("&input=" + URLEncoder.encode(input, "utf8"));
            Log.d(LOG_TAG, "Calling "+sb.toString()) ;
    
            URL url = new URL(sb.toString());
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
    
            // Load the results into a StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                jsonResults.append(buff, 0, read);
            }
        } catch (MalformedURLException e) {
            Log.e(LOG_TAG, "Error processing Places API URL", e);
            return resultList;
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error connecting to Places API", e);
            return resultList;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    
        try {
            // Create a JSON object hierarchy from the results
            JSONObject jsonObj = new JSONObject(jsonResults.toString());
            JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
    
            // Extract the Place descriptions from the results
            resultList = new ArrayList<String>(predsJsonArray.length());
            for (int i = 0; i < predsJsonArray.length(); i++) {
                resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, "Cannot process JSON results", e);
        }
    
        Log.d(LOG_TAG, resultList.size() + " in total returned.") ;
    
        return resultList;
    }
    
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        Double latitude, longitude;
        ArrayList<String> resultList = null;
        HttpURLConnection conn = null;
        StringBuilder jsonResults = new StringBuilder();
        String str = (String) adapterView.getItemAtPosition(position);
        try {
            StringBuilder sb = new StringBuilder(
                    "http://maps.googleapis.com/maps/api/geocode/json?" + "address="
                            + URLEncoder.encode(str, "utf-8") + "&sensor=true");
    
            URL url = new URL(sb.toString());
            Log.d("Taxeeta", url.toString() + " Called");
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
    
            // Load the results into a StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                jsonResults.append(buff, 0, read);
            }
        } catch (MalformedURLException e) {
            Log.e("Taxeeta", "Error processing Places API URL", e);
        } catch (IOException e) {
            Log.e("Taxeeta", "Error connecting to Places API", e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    
        try {
            // Create a JSON object hierarchy from the results
            JSONObject jsonObj = new JSONObject(jsonResults.toString());
            JSONObject location = ((JSONObject) jsonObj.getJSONArray("results").get(0))
                    .getJSONObject("geometry").getJSONObject("location");
            latitude = location.optDouble("lat");
            longitude = location.optDouble("lng");
            Log.d("Taxeeta", "Received Latitude " + latitude + ": Longitude" + longitude);
            if (view.getId() == fromAddress.getId()) {
                source = new GeoPoint((int) (latitude * 1E6), (int) (longitude * 1E6));
                Log.d("Taxeeta", "Source Done");
            } else {
                destination = new GeoPoint((int) (latitude * 1E6), (int) (longitude * 1E6));
                Log.d("Taxeeta", "Destination Done");
            }
        } catch (JSONException e) {
            Log.e("Taxeeta", "Cannot process JSON results", e);
        }
    }