2011-06-27 33 views
5

在我的應用程序中,我有一個活動,延伸MapActivity。並在那裏我把AutoCompleteTextView和一個名爲「搜索」的按鈕,所以我在AutoCompleteTextView內寫入,然後按搜索按鈕,它會轉到Google地圖中的那個位置。 AutoCompleteTextView適用於我在strings.xml中提及的小項目。 但我想它應該作爲谷歌搜索引擎,就像在谷歌搜索框中,無論我們開始寫它自動完成每一個字。 事情是它需要從谷歌服務器的數據。是不是? 如果是這樣,那麼我如何將數據綁定到我的AutoCompleteTextView來自Google服務器,以便它可以用作Google搜索框。 我正在使用android API v2.2。android如何使AutoCompleteTextView工作爲谷歌搜索框

回答

2

你必須使用谷歌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) { 

} });