android如何使AutoCompleteTextView作为谷歌搜索框工作

时间:2011-06-27 07:08:12

标签: android autocompletetextview

在我的应用程序中,我有一个扩展MapActivity的活动。然后我放了一个AutoCompleteTextView和一个名为“搜索”的按钮,这样我在AutoCompleteTextView内写的内容然后按搜索按钮就会转到Google地图中的该位置。 AutoCompleteTextView适用于我在 strings.xml 中提及的少量项目。 但我希望它应该像谷歌搜索引擎一样工作,就像谷歌搜索框一样,无论我们开始写什么,它都会自动完成每个单词。 事情是它从谷歌服务器获取数据。是不是? 如果是,那么如何将数据绑定到来自Google服务器的 AutoCompleteTextView ,以便它可以作为Google搜索框使用。 我使用的是android API v2.2。

2 个答案:

答案 0 :(得分:2)

您必须使用Google Places API,首先需要生成场所API密钥,请查看此页:

http://code.google.com/apis/maps/documentation/places/

在我的情况下,我使用了这段代码:

 final ArrayAdapter<String> adapter = new ArrayAdapter<String> (this,R.layout.list_item);    
AutoCompleteTextView textView = (AutoCompleteTextView)   findViewById(R.id.autoCompleteTextView1);   
adapter.setNotifyOnChange(true);   
textView.setAdapter(adapter);   
textView.addTextChangedListener(new TextWatcher() {

   public void onTextChanged(CharSequence s, int start, int before, int count) {    if (count%3 == 1) {    adapter.clear();   try {

        URL googlePlaces = new URL(
        // URLEncoder.encode(url,"UTF-8");
                "https://maps.googleapis.com/maps/api/place/autocomplete/json?input="+ URLEncoder.encode(s.toString(), "UTF-8")
+"&types=geocode&language=fr&sensor=true&key=<getyourAPIkey>");
        URLConnection tc = googlePlaces.openConnection();
        Log.d("GottaGo", URLEncoder.encode(s.toString()));
        BufferedReader in = new BufferedReader(new InputStreamReader(
                tc.getInputStream()));

        String line;
        StringBuffer sb = new StringBuffer();
        while ((line = in.readLine()) != null) {
        sb.append(line);
        }
        JSONObject predictions = new JSONObject(sb.toString());            
        JSONArray ja = new JSONArray(predictions.getString("predictions"));

            for (int i = 0; i < ja.length(); i++) {
                JSONObject jo = (JSONObject) ja.get(i);
                adapter.add(jo.getString("description"));
            }


    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   }        

 }

public void beforeTextChanged(CharSequence s, int start, int count,   int after) {  // TODO Auto-generated method stub

   }

public void afterTextChanged(Editable s) {

} });

答案 1 :(得分:1)

带有Google搜索Api的AutoCompleteTextView

enter image description here

您的xml

<AutoCompleteTextView
android:id="@+id/main_omnibox_input"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="@null" 
android:hint="Search"  
android:focusable="true"
android:focusableInTouchMode="true"                                  
android:selectAllOnFocus="true"
android:singleLine="true" 
android:textSize="@dimen/_14sdp" />

Activity.java

this.inputBox = (AutoCompleteTextView) findViewById(R.id.main_omnibox_input);
inputBox.setAdapter(new SearchAutocompleteAdapter(SearchActivity.this, new 
SearchAutocompleteAdapter.OnSearchCommitListener() {
    @Override
    public void onSearchCommit(String text) {
        inputBox.setText(text);
        inputBox.setSelection(text.length());
    }
}));


this.inputBox.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
        String charSequence = ((TextView) view.findViewById(android.R.id.text1)).getText().toString();
        inputBox.setText(Html.fromHtml(BrowserUnit.urlWrapper(charSequence)), BufferType.SPANNABLE);
        inputBox.setSelection(charSequence.length());
       // your code
       // updateAlbum(charSequence);
       // hideSoftInput(SearchActivity.this.inputBox);
    }
});

SearchAdapter看起来像

public class SearchAutocompleteAdapter extends BaseAdapter implements Filterable {

        interface OnSearchCommitListener {
            void onSearchCommit(String text);
        }

        private final Context mContext;
        private final OnSearchCommitListener commitListener;
        private List<String> completions = new ArrayList<>();
        static final String searchCompleteUrl = "https://www.google.com/complete/search?client=firefox&q=%s";

        SearchAutocompleteAdapter(Context context, OnSearchCommitListener commitListener) {
            mContext = context;
            this.commitListener = commitListener;
        }

        @Override
        public int getCount() {
            return completions.size();
        }

        @Override
        public Object getItem(int position) {
            return completions.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressLint("ClickableViewAccessibility")
        @Override
        @SuppressWarnings("ConstantConditions")
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
            }
            TextView textview = convertView.findViewById(android.R.id.text1);
            textview.setText(completions.get(position));
            Drawable d = ContextCompat.getDrawable(mContext, R.drawable.icon_goarrowsmall);
            final int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32, mContext.getResources().getDisplayMetrics());
            d.setBounds(0, 0, size, size);
            textview.setCompoundDrawables(null, null, d, null);

            textview.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent event) {
                    if (event.getAction() != MotionEvent.ACTION_DOWN) {
                        return false;
                    }
                    TextView t = (TextView) view;
                    if (event.getX() > t.getWidth() - t.getCompoundPaddingRight()) {
                        commitListener.onSearchCommit(getItem(position).toString());
                        return true;
                    }
                    return false;
                }
            });
            parent.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent event) {
                    if (event.getX() > view.getWidth() - size * 2) {
                        return true;
                    }
                    return false;
                }
            });
            return convertView;
        }

        @Override
        public Filter getFilter() {
            return new Filter() {
                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                    // Invoked on a worker thread
                    FilterResults filterResults = new FilterResults();
                    if (constraint != null) {
                        List<String> results = getCompletions(constraint.toString());
                        filterResults.values = results;
                        filterResults.count = results.size();
                    }
                    return filterResults;
                }

                @Override
                @SuppressWarnings("unchecked")
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    if (results != null && results.count > 0) {
                        completions = (List<String>) results.values;
                        notifyDataSetChanged();
                    } else {
                        notifyDataSetInvalidated();
                    }
                }
            };
        }

        private List<String> getCompletions(String text) {
            int total = 0;
            byte[] data = new byte[16384];
            try {
                URL url = new URL(URLUtil.composeSearchUrl(text, searchCompleteUrl, "%s"));
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                try {
                    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                    while (total <= data.length) {
                        int count = in.read(data, total, data.length - total);
                        if (count == -1) {
                            break;
                        }
                        total += count;
                    }
                    if (total == data.length) {
                        // overflow
                        return new ArrayList<>();
                    }
                } finally {
                    urlConnection.disconnect();
                }
            } catch (IOException e) {
                return new ArrayList<>();
            }

            JSONArray jsonArray;
            try {
                jsonArray = new JSONArray(new String(data, StandardCharsets.UTF_8));
            } catch (JSONException e) {
                return new ArrayList<>();
            }
            jsonArray = jsonArray.optJSONArray(1);
            if (jsonArray == null) {
                return new ArrayList<>();
            }
            final int MAX_RESULTS = 10;
            List<String> result = new ArrayList<>(Math.min(jsonArray.length(), MAX_RESULTS));
            for (int i = 0; i < jsonArray.length() && result.size() < MAX_RESULTS; i++) {
                String s = jsonArray.optString(i);
                if (s != null && !s.isEmpty()) {
                    result.add(s);
                }
            }
            return result;
        }
    }