В моем приложении у меня есть действие, которое расширяет MapActivity
. и там я помещаю AutoCompleteTextView
и кнопку под названием «Поиск», поэтому то, что я пишу в AutoCompleteTextView
И нажимаю кнопку «Поиск», переходит в это место на карте Google. AutoCompleteTextView
для небольшого количества элементов, которые я упоминаю в strings.xml. Но я хочу, чтобы он работал как поисковая система Google, как в окне поиска Google, что бы мы ни начали писать, оно автоматически завершает каждое слово. Дело в том, что он берет данные с сервера Google. А это не? Если это так, то как я могу связать данные с моим AutoCompleteTextView с сервера Google, чтобы он работал как окно поиска Google. Я использую Android API v2.2.
Android, как заставить AutoCompleteTextView работать как окно поиска Google
Ответы (2)
Вы должны использовать API Google Places, вам нужно сначала сгенерировать ключ 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) {
} });
person
Nibha Jain
schedule
04.12.2011
AutoCompleteTextView с API поиска Google
ваш 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;
}
}
person
jay patoliya
schedule
23.07.2020