Android-放置自动完成EditText不会显示结果

时间:2018-12-18 19:56:52

标签: java android

我正试图允许用户填写一些联系方式,其中之一就是联系地址。我已按照本(https://www.youtube.com/watch?v=6Trdd9EnmqY)教程进行操作,但似乎没有任何效果。

“地点自动完成”是否必须在“地图活动”中? 另外,我对视频不了解的是应该将结果显示在哪个视图(例如ListView)上。

从Google的GitHub示例中获取的适配器类:

public class GooglePlacesAutocompleteAdapter
extends ArrayAdapter<AutocompletePrediction> implements Filterable {

private static final String TAG = "PlaceAutoCompleteAd";
  private static final CharacterStyle STYLE_BOLD = new StyleSpan(Typeface.BOLD);
  private ArrayList<AutocompletePrediction> mResultList;
  private GoogleApiClient mGoogleApiClient;
  private LatLngBounds mBounds;
  private AutocompleteFilter mPlaceFilter;

  public GooglePlacesAutocompleteAdapter(Context context, GoogleApiClient googleApiClient,
                                         LatLngBounds bounds, AutocompleteFilter filter) {
    super(context, android.R.layout.simple_expandable_list_item_2, android.R.id.text1);
    mGoogleApiClient = googleApiClient;
    mBounds = bounds;
    mPlaceFilter = filter;
  }

  public void setBounds(LatLngBounds bounds) {
    mBounds = bounds;
  }

  @Override
  public int getCount() {
    return mResultList.size();
  }

  @Override
  public AutocompletePrediction getItem(int position) {
    return mResultList.get(position);
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    View row = super.getView(position, convertView, parent);

    AutocompletePrediction item = getItem(position);

    TextView textView1 = (TextView) row.findViewById(android.R.id.text1);
    TextView textView2 = (TextView) row.findViewById(android.R.id.text2);
    textView1.setText(item.getPrimaryText(STYLE_BOLD));
    textView2.setText(item.getSecondaryText(STYLE_BOLD));

    return row;
  }

  @Override
  public Filter getFilter() {
    return new Filter() {
      @Override
      protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();

        ArrayList<AutocompletePrediction> filterData = new ArrayList<>();

        if (constraint != null) {
          filterData = getAutocomplete(constraint);
        }

        results.values = filterData;
        if (filterData != null) {
          results.count = filterData.size();
        } else {
          results.count = 0;
        }

        return results;
      }

      @Override
      protected void publishResults(CharSequence constraint, FilterResults results) {

        if (results != null && results.count > 0) {
          mResultList = (ArrayList<AutocompletePrediction>) results.values;
          notifyDataSetChanged();
        } else {
          // The API did not return any results, invalidate the data set.
          notifyDataSetInvalidated();
        }
      }

      @Override
      public CharSequence convertResultToString(Object resultValue) {
        if (resultValue instanceof AutocompletePrediction) {
          return ((AutocompletePrediction) resultValue).getFullText(null);
        } else {
          return super.convertResultToString(resultValue);
        }
      }
    };
  }

  private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) {
    if (mGoogleApiClient.isConnected()) {
      Log.i(TAG, "Starting autocomplete query for: " + constraint);

      PendingResult<AutocompletePredictionBuffer> results =
          Places.GeoDataApi
              .getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
                  mBounds, mPlaceFilter);

      AutocompletePredictionBuffer autocompletePredictions = results
          .await(60, TimeUnit.SECONDS);

      final Status status = autocompletePredictions.getStatus();
      if (!status.isSuccess()) {
        Toast.makeText(getContext(), "Error contacting API: " + status.toString(),
            Toast.LENGTH_SHORT).show();
        Log.e(TAG, "Error getting autocomplete prediction API call: " + status.toString());
        autocompletePredictions.release();
        return null;
      }

      Log.i(TAG, "Query completed. Received " + autocompletePredictions.getCount()
          + " predictions.");

      return DataBufferUtils.freezeAndClose(autocompletePredictions);
    }
    Log.e(TAG, "Google API client is not connected for autocomplete query.");
    return null;
  }
}

ContactAddActivity:-从onCreate方法调用init()。

private void init() {
    autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.locationField);
    googlePlacesAutocompleteAdapter = new GooglePlacesAutocompleteAdapter(this, googleApiClient, LAT_LNG_BOUNDS, null);
    autoCompleteTextView.setAdapter(googlePlacesAutocompleteAdapter);

    googleApiClient = new GoogleApiClient.Builder(this)
        .addApi(Places.GEO_DATA_API)
        .addApi(Places.PLACE_DETECTION_API)
        .enableAutoManage(this, this)
        .build();

    autoCompleteTextView.setOnEditorActionListener(new AutoCompleteTextView.OnEditorActionListener() {
      @Override
      public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
        if(actionId == EditorInfo.IME_ACTION_SEARCH
            || actionId == EditorInfo.IME_ACTION_DONE
            || keyEvent.getAction() == KeyEvent.ACTION_DOWN
            || keyEvent.getAction() == KeyEvent.KEYCODE_ENTER){

          //execute our method for searching
          geoLocate();
        }
        return false;
      }
    });
  }

  private void geoLocate(){
    Log.d("MSG", "geoLocate: geolocating");

    String searchString = autoCompleteTextView.getText().toString();

    Geocoder geocoder = new Geocoder(ContactAddActivity.this);
    List<Address> list = new ArrayList<>();
    try{
      list = geocoder.getFromLocationName(searchString, 1);
    }catch (IOException e){
      Log.e("MSG", "geoLocate: IOException: " + e.getMessage() );
    }

    if(list.size() > 0){
      Address address = list.get(0);

      Log.d("MSG", "geoLocate: found a location: " + address.toString());
      //Toast.makeText(this, address.toString(), Toast.LENGTH_SHORT).show();
    }
  }

contact_add_activity.xml:

<RelativeLayout 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:id="@+id/addContactRelLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:padding="20dp"
    tools:context=".Activities.ContactAddActivity">

<EditText
    android:id="@+id/firstNameTextField"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_marginBottom="20dp"
    android:backgroundTint="@color/colorLandingScreenFAB"
    android:fontFamily="@font/cairo"
    android:inputType="textCapWords"
    android:hint="First Name"
    android:singleLine="true" />

<EditText
    android:id="@+id/lastNameTextField"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_marginBottom="20dp"
    android:hint="Last Name"
    android:singleLine="true"
    android:layout_below="@id/firstNameTextField"
    android:inputType="textCapWords"
    android:fontFamily="@font/cairo"
    android:backgroundTint="@color/colorLandingScreenFAB"/>

<EditText
    android:id="@+id/emailTextField"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_marginBottom="20dp"
    android:hint="Email Address"
    android:singleLine="true"
    android:layout_below="@id/lastNameTextField"
    android:fontFamily="@font/cairo"
    android:inputType="textEmailAddress"
    android:backgroundTint="@color/colorLandingScreenFAB"/>

<EditText
    android:id="@+id/phoneNumberTextField"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_marginBottom="20dp"
    android:hint="Phone Number"
    android:singleLine="true"
    android:layout_below="@id/emailTextField"
    android:fontFamily="@font/cairo"
    android:inputType="number"
    android:backgroundTint="@color/colorLandingScreenFAB"/>

<AutoCompleteTextView
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:hint="Address"
    android:layout_below="@id/phoneNumberTextField"
    android:id="@+id/locationField"
    android:textColor="@color/colorActionBarText"
    android:fontFamily="@font/cairo"
    android:backgroundTint="#00000000"
    android:gravity="center_vertical"/>

<Button
    android:id="@+id/addContactButton"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_below="@id/locationField"
    android:layout_marginTop="30dp"
    android:text="Add"
    android:textColor="#ffffff"
    android:textSize="18sp"
    android:background="@drawable/add_contact_save_button"
    android:fontFamily="@font/cairo"
    android:onClick="addContact"/>

</RelativeLayout>

0 个答案:

没有答案