
放置适配器类: –
package com.example.keita.Googleplaces;import androID.content.Context;import androID.util.Log;import androID.Widget.ArrayAdapter;import androID.Widget.Filter;import androID.Widget.Filterable;import androID.Widget.Toast;import com.Google.androID.gms.common.API.Googleapiclient;import com.Google.androID.gms.common.API.PendingResult;import com.Google.androID.gms.common.API.Status;import com.Google.androID.gms.location.places.autocompleteFilter;import com.Google.androID.gms.location.places.autocompletePrediction;import com.Google.androID.gms.location.places.autocompletePredictionBuffer;import com.Google.androID.gms.location.places.Places;import com.Google.androID.gms.maps.model.LatLngBounds;import java.util.ArrayList;import java.util.Iterator;import java.util.concurrent.TimeUnit;public class PlaceArrayAdapter extends ArrayAdapter<PlaceArrayAdapter.Placeautocomplete> implements Filterable { private static final String TAG = "PlaceArrayAdapter"; private Googleapiclient mGoogleapiclient; private autocompleteFilter mPlaceFilter; private LatLngBounds mBounds; private ArrayList<Placeautocomplete> mResultList; /** * Constructor * * @param context Context * @param resource Layout resource * @param bounds Used to specify the search bounds * @param filter Used to specify place types */ public PlaceArrayAdapter(Context context,int resource,LatLngBounds bounds,autocompleteFilter filter) { super(context,resource); mBounds = bounds; mPlaceFilter = filter; } public voID setGoogleapiclient(Googleapiclient Googleapiclient) { if (Googleapiclient == null || !Googleapiclient.isConnected()) { mGoogleapiclient = null; } else { mGoogleapiclient = Googleapiclient; } } @OverrIDe public int getCount() { return mResultList.size(); } @OverrIDe public Placeautocomplete getItem(int position) { return mResultList.get(position); } private ArrayList<Placeautocomplete> getPredictions(CharSequence constraint) { if (mGoogleapiclient != null) { Log.i(TAG,"Executing autocomplete query for: " + constraint); PendingResult<autocompletePredictionBuffer> results = Places.GeoDataAPI .getautocompletePredictions(mGoogleapiclient,constraint.toString(),mBounds,mPlaceFilter); // Wait for predictions,set the timeout. autocompletePredictionBuffer autocompletePredictions = results .await(60,TimeUnit.SECONDS); final Status status = autocompletePredictions.getStatus(); if (!status.isSuccess()) { Toast.makeText(getContext(),"Error: " + status.toString(),Toast.LENGTH_SHORT).show(); Log.e(TAG,"Error getting place predictions: " + status .toString()); autocompletePredictions.release(); return null; } Log.i(TAG,"query completed. Received " + autocompletePredictions.getCount() + " predictions."); Iterator<autocompletePrediction> iterator = autocompletePredictions.iterator(); ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount()); while (iterator.hasNext()) { autocompletePrediction prediction = iterator.next(); resultList.add(new Placeautocomplete(prediction.getPlaceID(),prediction.getDescription())); } // Buffer release autocompletePredictions.release(); return resultList; } Log.e(TAG,"Google Api clIEnt is not connected."); return null; } @OverrIDe public Filter getFilter() { Filter filter = new Filter() { @OverrIDe protected FilterResults performFiltering(CharSequence constraint) { FilterResults results = new FilterResults(); if (constraint != null) { // query the autocomplete API for the entered constraint mResultList = getPredictions(constraint); if (mResultList != null) { // Results results.values = mResultList; results.count = mResultList.size(); } } return results; } @OverrIDe protected voID publishResults(CharSequence constraint,FilterResults results) { if (results != null && results.count > 0) { // The API returned at least one result,update the data. notifyDataSetChanged(); } else { // The API dID not return any results,invalIDate the data set. notifyDataSetInvalIDated(); } } }; return filter; } class Placeautocomplete { public CharSequence placeID; public CharSequence description; Placeautocomplete(CharSequence placeID,CharSequence description) { this.placeID = placeID; this.description = description; } @OverrIDe public String toString() { return description.toString(); } }} MainActivity类: –
package com.example.keita.Googleplaces;import androID.os.Bundle;import androID.support.design.Widget.floatingActionbutton;import androID.support.design.Widget.Snackbar;import androID.support.v7.app.AppCompatActivity;import androID.support.v7.Widget.Toolbar;import androID.vIEw.VIEw;import androID.vIEw.Menu;import androID.vIEw.MenuItem;import androID.os.Bundle;import androID.support.v7.app.AppCompatActivity;import androID.text.HTML;import androID.util.Log;import androID.vIEw.VIEw;import androID.Widget.AdapterVIEw;import androID.Widget.autoCompleteTextVIEw;import androID.Widget.TextVIEw;import androID.Widget.Toast;import com.Google.androID.gms.common.ConnectionResult;import com.Google.androID.gms.common.API.Googleapiclient;import com.Google.androID.gms.common.API.PendingResult;import com.Google.androID.gms.common.API.ResultCallback;import com.Google.androID.gms.location.places.Place;import com.Google.androID.gms.location.places.PlaceBuffer;import com.Google.androID.gms.location.places.Places;import com.Google.androID.gms.maps.model.LatLng;import com.Google.androID.gms.maps.model.LatLngBounds;public class MainActivity extends AppCompatActivity implements Googleapiclient.OnConnectionFailedListener,Googleapiclient.ConnectionCallbacks{ private static final String LOG_TAG = "MainActivity"; private static final int Google_API_CLIENT_ID = 0; private autoCompleteTextVIEw mautocompleteTextVIEw; private TextVIEw mnameTextVIEw; private TextVIEw mAddresstextVIEw; private TextVIEw mIDTextVIEw; private TextVIEw mPhoneTextVIEw; private TextVIEw mWebTextVIEw; private TextVIEw mAttTextVIEw; private Googleapiclient mGoogleapiclient; private PlaceArrayAdapter mPlaceArrayAdapter; private static final LatLngBounds LAT_LNG_BOUNDS = new LatLngBounds( new LatLng(32.6393,-117.004304),new LatLng(44.901184,-67.32254)); @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); Toolbar toolbar = (Toolbar) findVIEwByID(R.ID.toolbar); setSupportActionbar(toolbar); floatingActionbutton fab = (floatingActionbutton) findVIEwByID(R.ID.fab); fab.setonClickListener(new VIEw.OnClickListener() { @OverrIDe public voID onClick(VIEw vIEw) { Snackbar.make(vIEw,"Replace with your own action",Snackbar.LENGTH_LONG) .setAction("Action",null).show(); } }); mGoogleapiclient = new Googleapiclient.Builder(MainActivity.this) .addAPI(Places.GEO_DATA_API) .enableautoManage(this,Google_API_CLIENT_ID,this) .addConnectionCallbacks(this) .build(); mautocompleteTextVIEw = (autoCompleteTextVIEw) findVIEwByID(R.ID .autoCompleteTextVIEw); mautocompleteTextVIEw.setThreshold(3); mnameTextVIEw = (TextVIEw) findVIEwByID(R.ID.name); mAddresstextVIEw = (TextVIEw) findVIEwByID(R.ID.address); mIDTextVIEw = (TextVIEw) findVIEwByID(R.ID.place_ID); mPhoneTextVIEw = (TextVIEw) findVIEwByID(R.ID.phone); mWebTextVIEw = (TextVIEw) findVIEwByID(R.ID.web); mAttTextVIEw = (TextVIEw) findVIEwByID(R.ID.att); mautocompleteTextVIEw.setonItemClickListener(mautocompleteClickListener); mPlaceArrayAdapter = new PlaceArrayAdapter(this,androID.R.layout.simple_List_item_1,LAT_LNG_BOUNDS,null); mautocompleteTextVIEw.setAdapter(mPlaceArrayAdapter); } private AdapterVIEw.OnItemClickListener mautocompleteClickListener = new AdapterVIEw.OnItemClickListener() { @OverrIDe public voID onItemClick(AdapterVIEw<?> parent,VIEw vIEw,int position,long ID) { final PlaceArrayAdapter.Placeautocomplete item = mPlaceArrayAdapter.getItem(position); final String placeID = String.valueOf(item.placeID); Log.i(LOG_TAG,"Selected: " + item.description); PendingResult<PlaceBuffer> placeResult = Places.GeoDataAPI .getPlaceByID(mGoogleapiclient,placeID); placeResult.setResultCallback(mUpdatePlaceDetailsCallback); Log.i(LOG_TAG,"Fetching details for ID: " + item.placeID); } }; private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback = new ResultCallback<PlaceBuffer>() { @OverrIDe public voID onResult(PlaceBuffer places) { if (!places.getStatus().isSuccess()) { Log.e(LOG_TAG,"Place query dID not complete. Error: " + places.getStatus().toString()); return; } // Selecting the first object buffer. final Place place = places.get(0); CharSequence attributions = places.getAttributions(); mnameTextVIEw.setText(HTML.fromHTML(place.getname() + "")); mAddresstextVIEw.setText(HTML.fromHTML(place.getAddress() + "")); mIDTextVIEw.setText(HTML.fromHTML(place.getID() + "")); mPhoneTextVIEw.setText(HTML.fromHTML(place.getPhoneNumber() + "")); mWebTextVIEw.setText(place.getWebsiteUri() + ""); if (attributions != null) { mAttTextVIEw.setText(HTML.fromHTML(attributions.toString())); } } }; @OverrIDe public voID onConnected(Bundle bundle) { mPlaceArrayAdapter.setGoogleapiclient(mGoogleapiclient); Log.i(LOG_TAG,"Google Places API connected."); } @OverrIDe public voID onConnectionFailed(ConnectionResult connectionResult) { Log.e(LOG_TAG,"Google Places API connection Failed with error code: " + connectionResult.getErrorCode()); Toast.makeText(this,"Google Places API connection Failed with error code:" + connectionResult.getErrorCode(),Toast.LENGTH_LONG).show(); } @OverrIDe public voID onConnectionSuspended(int i) { mPlaceArrayAdapter.setGoogleapiclient(null); Log.e(LOG_TAG,"Google Places API connection suspended."); } @OverrIDe public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main,menu); return true; } @OverrIDe public boolean onoptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button,so long // as you specify a parent activity in AndroIDManifest.xml. int ID = item.getItemID(); //noinspection SimplifiableIfStatement if (ID == R.ID.action_settings) { return true; } return super.onoptionsItemSelected(item); }} content_main.xml: –
<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:app="http://schemas.androID.com/apk/res-auto" xmlns:tools="http://schemas.androID.com/tools" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:orIEntation="vertical" androID:paddingBottom="@dimen/activity_vertical_margin" androID:paddingleft="@dimen/activity_horizontal_margin" androID:paddingRight="@dimen/activity_horizontal_margin" androID:paddingtop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_vIEw_behavior" tools:context="com.example.keita.Googleplaces.MainActivity" tools:showIn="@layout/activity_main"> <autoCompleteTextVIEw androID:ID="@+ID/autoCompleteTextVIEw" androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:layout_centerHorizontal="true" androID:layout_margintop="50dp" androID:hint="Enter Place Here"/> <TextVIEw androID:ID="@+ID/header" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_alignParentleft="true" androID:layout_alignParentStart="true" androID:layout_below="@+ID/autoCompleteTextVIEw" androID:layout_margintop="20dp" androID:text="Selected Place:" androID:textStyle="bold"/> <TextVIEw androID:ID="@+ID/name" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_alignParentleft="true" androID:layout_alignParentStart="true" androID:layout_below="@+ID/header" androID:layout_margintop="20dp"/> <TextVIEw androID:ID="@+ID/address" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_alignParentleft="true" androID:layout_alignParentStart="true" androID:layout_below="@+ID/name"/> <TextVIEw androID:ID="@+ID/place_ID" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_alignParentleft="true" androID:layout_alignParentStart="true" androID:layout_below="@+ID/address"/> <TextVIEw androID:ID="@+ID/phone" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_alignParentleft="true" androID:layout_alignParentStart="true" androID:layout_below="@+ID/place_ID" androID:autolink="phone"/> <TextVIEw androID:ID="@+ID/web" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_alignParentleft="true" androID:layout_alignParentStart="true" androID:layout_below="@+ID/phone" androID:autolink="web"/> <TextVIEw androID:ID="@+ID/att" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_alignParentBottom="true" androID:layout_alignParentEnd="true" androID:layout_alignParentRight="true" androID:autolink="web"/> ImageVIEw androID:ID="@+ID/poweredBy" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_above="@+ID/att" androID:layout_alignParentEnd="true" androID:layout_alignParentRight="true" androID:src="@drawable/powered_by_Google_light"/> ImageVIEw androID:ID="@+ID/truiton_image" androID:layout_wIDth="100dp" androID:layout_height="100dp" androID:layout_above="@+ID/poweredBy" androID:layout_alignParentEnd="true" androID:layout_alignParentRight="true" androID:layout_marginBottom="-20dp" androID:src="@mipmap/ic_launcher"/></linearLayout>解决方法 在AndroID中我们可以这样限制:
在代码中添加autoCompletionFilter而不是传递null
限制谷歌自动补充到澳大利亚.
autocompleteFilter filter = new autocompleteFilter.Builder().setCountry("AU").build(); 将结果限制为的国家/地区.这应该是ISO 3166-1 Alpha-2国家/地区代码(不区分大小写).如果未设置,则不会进行国家/地区过滤.
请参阅此链接以获取不同的国家代码https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
@Saipraneeth Nandi纠正你的代码行如下:
mPlaceArrayAdapter = new PlaceArrayAdapter(this,filter);总结
以上是内存溢出为你收集整理的android – 如何限制谷歌地方自动完成到特定国家/地区?全部内容,希望文章能够帮你解决android – 如何限制谷歌地方自动完成到特定国家/地区?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)