2014-03-12 74 views
0

我的地圖頁上有一個AutoCompleteTextView。它工作得很好,預測的選項正是我希望他們成爲的。但是,當用戶點擊其中一個預測(或自己輸入地址)後,我想將AutoComplete視圖中的地址更改爲一個字符串,並根據此地址獲取經度和緯度。我想這時候他按下完成按鈕上繼keyboardThe是我這個AutoCompleteTextView setOnKeyListener未被執行

from_loc = (AutoCompleteTextView) findViewById(R.id.from_address); 
from_loc.setAdapter(new PlacesAutoCompleteAdapter(this, R.layout.list_item)); 

from_loc.setOnKeyListener(new OnKeyListener() { 

     @Override 
     public boolean onKey(View v, int keyCode, KeyEvent event) { 
      if(keyCode == KeyEvent.KEYCODE_ENTER){ 

       JSONObject startObj = new JSONObject(); 
       startObj = getLocationInfo(from_loc.getText().toString()); 

       try { 
        double start_lat = ((JSONArray)startObj.get("results")).getJSONObject(0) 
          .getJSONObject("geometry").getJSONObject("location") 
          .getDouble("lng"); 

        double start_long = ((JSONArray)startObj.get("results")).getJSONObject(0) 
          .getJSONObject("geometry").getJSONObject("location") 
          .getDouble("lat"); 

        MarkerOptions marker = new MarkerOptions().position(new LatLng(start_lat, start_long)).title("Place1"); 

        map.addMarker(marker); 
       } catch (JSONException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
       return true; 
      } 
      return false; 
     } 

    }); 

代碼我getLocationInfo方法如下進行:

public static JSONObject getLocationInfo(String address) { 

    StringBuilder stringBuilder = new StringBuilder(); 

    try { 
     address = address.replaceAll(" ","%20");  

     HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false"); 
     HttpClient client = new DefaultHttpClient(); 
     HttpResponse response; 
     stringBuilder = new StringBuilder(); 


     response = client.execute(httppost); 
     HttpEntity entity = response.getEntity(); 
     InputStream stream = entity.getContent(); 
     int b; 
     while ((b = stream.read()) != -1) { 
      stringBuilder.append((char) b); 
     } 
    } catch (ClientProtocolException e) { 
    } catch (IOException e) { 
    } 

    JSONObject jsonObject = new JSONObject(); 
    try { 
     jsonObject = new JSONObject(stringBuilder.toString()); 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    return jsonObject; 
} 

但這種代碼是行不通的。即使當我試圖在另一個普通文本視圖中顯示AutoComplete文本視圖中的文本時,它也沒有發生。實際上,當我調試代碼時,我意識到它不會進入from_loc.setOnKeyListener部分,但不知道需要做什麼。我甚至嘗試着爲Adapter實施Listener,但沒有發生任何事情。

回答

0

您是否正在使用軟鍵盤(IME)? OnKeyListener只能通過硬件鍵盤的事件進行調用。您可以使用:

或者

[來源:http://developer.android.com/reference/android/view/View.OnKeyListener.html]