【问题标题】:Customise PlaceAutocomplete自定义地点自动完成
【发布时间】:2019-02-24 07:40:25
【问题描述】:

我正在开发一个安卓应用程序。在那里有一个google mapplaces 搜索。当我在搜索视图上搜索地点时,我得到了

Peringathur,Kerala, India
Peringavu, Thrissur, Kerala, India
Peringala,Kerala, India
Peringalkuthu Dam, Poringalkuthu, Pariyaram, Kerala, India
Peringandoor, Kerala, India

这里我需要从所有行中删除这个Kerala, India

 Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
        ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount());
        while (iterator.hasNext()) {
            AutocompletePrediction prediction = iterator.next();
            String data = (String) prediction.getFullText(null);

            resultList.add(new PlaceAutocomplete(prediction.getPlaceId(),
                    (String) prediction.getPrimaryText(null)+"\n"+
                            (String) prediction.getSecondaryText(null)
));

【问题讨论】:

    标签: android google-maps google-places-api


    【解决方案1】:

    您可以像this 文章中那样使用自定义的AutoCompleteTextView。在results.values;Task&lt;AutocompletePredictionBufferResponse&gt; 填写地点列表后,您可以在protected void publishResults(CharSequence constraint, FilterResults results) 中自定义地点名称。

    所以,对于MainActivity.java 喜欢:

    public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
    
        private static final String TAG = MainActivity.class.getSimpleName();
        private GoogleMap mGoogleMap;
        private SupportMapFragment mMapSupportedFragment;
    
        private AutoCompleteTextView mPlaceAutoCompleteTextView;
        private PlacesAdapter mPlacesAdapter;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            mPlacesAdapter = new PlacesAdapter(this);
            mPlaceAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.place_autocomplete);
            mPlaceAutoCompleteTextView.setThreshold(1);
            mPlaceAutoCompleteTextView.setAdapter(mPlacesAdapter);
    
            mMapSupportedFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_fragment);
            mMapSupportedFragment.getMapAsync(MainActivity.this);
        }
    
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mGoogleMap = googleMap;
        }
    
        class PlacesAdapter extends ArrayAdapter {
            Context context;
            List<String> placesList = new ArrayList<>();
            GeoDataClient geoDataClient;
            PlacesAdapter.PlacesAutoCompleteFilter filter = new PlacesAdapter.PlacesAutoCompleteFilter();
    
            public PlacesAdapter(Context context) {
                super(context, android.R.layout.simple_dropdown_item_1line,
                        new ArrayList<Place>());
                this.context = context;
    
                geoDataClient = Places.getGeoDataClient(context, null);
            }
    
            @Override
            public int getCount() {
                return placesList.size();
            }
    
            @Override
            public String getItem(int position) {
                return placesList.get(position);
            }
    
            @Override
            public Filter getFilter() {
                return filter;
            }
    
            @Override
            public View getView(int position, View view, @NonNull ViewGroup parent) {
    
                if (view == null) {
                    view = LayoutInflater.from(parent.getContext())
                            .inflate(android.R.layout.simple_dropdown_item_1line,
                                    parent, false);
                }
    
                TextView textOne = view.findViewById(android.R.id.text1);
                textOne.setText(placesList.get(position));
    
                return view;
            }
    
            class PlacesAutoCompleteFilter extends Filter {
                private Object lock = new Object();
                private Object lockTwo = new Object();
                private boolean placeResults = false;
    
    
                @Override
                protected FilterResults performFiltering(CharSequence prefix) {
                    FilterResults results = new FilterResults();
                    placeResults = false;
                    final List<String> predictedPlacesList = new ArrayList<>();
    
                    if (prefix == null || prefix.length() == 0) {
                        synchronized (lock) {
                            results.values = new ArrayList<Place>();
                            results.count = 0;
                        }
                    } else {
                        final String searchStrLowerCase = prefix.toString().toLowerCase();
    
                        Task<AutocompletePredictionBufferResponse> task
                                = getAutoCompletePlaces(searchStrLowerCase);
    
                        task.addOnCompleteListener(new OnCompleteListener<AutocompletePredictionBufferResponse>() {
                            @Override
                            public void onComplete(@NonNull Task<AutocompletePredictionBufferResponse> task) {
                                if (task.isSuccessful()) {
                                    Log.d(TAG, "Auto complete prediction successful");
                                    AutocompletePredictionBufferResponse predictions = task.getResult();
                                    for (AutocompletePrediction prediction : predictions) {
                                        predictedPlacesList.add((prediction.getFullText(null)).toString());
                                    }
                                    predictions.release();
                                } else {
                                    Log.d(TAG, "Auto complete prediction unsuccessful");
                                }
    
                                placeResults = true;
                                synchronized (lockTwo) {
                                    lockTwo.notifyAll();
                                }
                            }
                        });
    
                        while (!placeResults) {
                            synchronized (lockTwo) {
                                try {
                                    lockTwo.wait();
                                } catch (InterruptedException e) {
    
                                }
                            }
                        }
                        results.values = predictedPlacesList;
                        results.count = predictedPlacesList.size();
                        Log.d(TAG, "Autocomplete predictions size after wait" + results.count);
                    }
    
                    return results;
                }
    
                @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    if (results.values != null) {
                        placesList = (ArrayList<String>) results.values;
                    } else {
                        placesList = null;
                    }
    
                    // customize your places here:
                    for (int i = 0; i < placesList.size(); i++) {
                        placesList.set(i, removeSuffix(placesList.get(i), "Kerala)); India");
                    }
    
                    if (results.count > 0) {
                        notifyDataSetChanged();
                    } else {
                        notifyDataSetInvalidated();
                    }
                }
    
                private Task<AutocompletePredictionBufferResponse> getAutoCompletePlaces(String query) {
                    AutocompleteFilter.Builder filterBuilder = new AutocompleteFilter.Builder();
    
                    Task<AutocompletePredictionBufferResponse> results =
                            geoDataClient.getAutocompletePredictions(query, null,
                                    filterBuilder.build());
                    return results;
                }
            }
        }
    
    
        public static String removeSuffix(final String s, final String suffix) {
            if (s != null && s.endsWith(suffix)) {
                return s.split(suffix)[0];
            }
            return s;
        }
    
    }
    

    activity_main.xml 可以是:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="<YOUR_PACKAGE_NAME>.MainActivity">
    
        <fragment class="com.google.android.gms.maps.SupportMapFragment"
            android:id="@+id/map_fragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />
    
        <AutoCompleteTextView android:id="@+id/place_autocomplete"
                              android:layout_width="match_parent"
                              android:layout_height="wrap_content"
                              android:background="@android:color/background_light"
                              android:layout_margin="16dp"
                              android:padding="8dp"
                              android:inputType="text"
                              android:imeOptions="actionNext"
                              android:textSize="16sp"
                              android:hint="Type place name here" />
    </RelativeLayout>
    

    注意!根据Usage Limits

    • 如果您的应用以编程方式使用自动完成服务,您的 UI
      必须要么显示“由 Google 提供支持”的署名,要么出现
      在 Google 品牌的地图中。

    【讨论】:

      猜你喜欢
      • 2016-06-30
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      • 1970-01-01
      • 2015-02-07
      • 2019-09-19
      • 2016-10-11
      • 1970-01-01
      相关资源
      最近更新 更多