android 如何使 AutoCompleteTextView 充当谷歌搜索框

发布于 2024-11-17 16:02:22 字数 427 浏览 4 评论 0原文

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

In my application I have an Activity which extends MapActivity. and there i put an AutoCompleteTextView and a button called "Search" so what i write within AutoCompleteTextView AND press Search button it goes to that location in Google map. AutoCompleteTextView is for small no of items which i mention in strings.xml.
But I want it should be worked as google search engine, like in google search box whatever we start to write it auto completes every word there.
Thing is that it takes data from google server. Is not it?
If it is, then how can i bind data to my AutoCompleteTextView from Google server so that it works as Google search box.
I am using android API v2.2.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

临风闻羌笛 2024-11-24 16:02:22

您必须使用 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) {

} });

You have to use Google Places API ,you need to generate a place API key first ,check this page :

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

In my case i have used this code :

 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) {

} });
酷炫老祖宗 2024-11-24 16:02:22

AutoCompleteTextView 与谷歌搜索 Api

在此处输入图像描述

您的 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;
        }
    }

AutoCompleteTextView with google search Api

enter image description here

your 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 looks like

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;
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文