【问题标题】:android how to make AutoCompleteTextView work as google search boxandroid如何使AutoCompleteTextView作为谷歌搜索框工作
【发布时间】:2011-06-27 07:08:11
【问题描述】:

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

【问题讨论】:

    标签: android autocompletetextview


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      带有谷歌搜索 API 的 AutoCompleteTextView

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

      【讨论】:

        猜你喜欢
        • 2021-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多