AutoCompleteTextView setOnKeyListener未被执行

时间:2014-03-12 21:15:17

标签: android autocompletetextview

我的地图页面上有AutoCompleteTextView。它工作得很好,预测的选项正是我想要的。但是在用户点击其中一个预测(或者自己输入地址)之后,我想将AutoComplete视图中的地址更改为字符串,并根据该地址获取经度和纬度。我希望在按下键盘上的完成按钮时完成此操作以下是我的代码

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部分,但不知道需要做什么。我甚至尝试为Listener实施Adapter但没有发生任何事情。

1 个答案:

答案 0 :(得分:0)

您使用的是软键盘(IME)吗?只有来自硬件键盘的事件才会调用OnKeyListener。您可以使用:

或者

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