次の名前の EditText があると仮定します: mapSearchBox
mapSearchBox = (EditText) findViewById(R.id.search);
mapSearchBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH ||
actionId == EditorInfo.IME_ACTION_DONE ||
actionId == EditorInfo.IME_ACTION_GO ||
event.getAction() == KeyEvent.ACTION_DOWN &&
event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
// hide virtual keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mapSearchBox.getWindowToken(), 0);
new SearchClicked(mapSearchBox.getText().toString()).execute();
mapSearchBox.setText("", TextView.BufferType.EDITABLE);
return true;
}
return false;
}
});
次に、リクエストを処理するために「SearchClicked」クラスが必要です。
private class SearchClicked extends AsyncTask<Void, Void, Boolean> {
private String toSearch;
private Address address;
public SearchClicked(String toSearch) {
this.toSearch = toSearch;
}
@Override
protected Boolean doInBackground(Void... voids) {
try {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.UK);
List<Address> results = geocoder.getFromLocationName(toSearch, 1);
if (results.size() == 0) {
return false;
}
address = results.get(0);
// Now do something with this GeoPoint:
GeoPoint p = new GeoPoint((int) (address.getLatitude() * 1E6), (int) (address.getLongitude() * 1E6))
} catch (Exception e) {
Log.e("", "Something went wrong: ", e);
return false;
}
return true;
}
}