在editText onClick中膨胀AutoCompleteSupportFragement

时间:2019-05-14 15:12:31

标签: android android-fragments android-edittext google-places-api onclicklistener

我正在尝试在editText的onClick事件中为使用Google Places API的AutoCompleteSupportFragment充气。

我想在单击editText时为该片段充气,以便用户输入位置,然后从自动完成片段的建议中选择,位置名称将显示在editText上。

我检查了此链接here,但对我来说无效。

places_auto_complete_fragment.xml

    <?xml version="1.0" encoding="utf-8"?>
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/place_autocomplete_fragment"
    android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment" />

我要如何为它充气

sourceEditText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            LayoutInflater layoutInflater = getLayoutInflater();
            layoutInflater.inflate(R.layout.places_auto_complete_fragment,addTripLinearLayout,false);
        }
    });

感谢您的帮助。谢谢

2 个答案:

答案 0 :(得分:1)

  1. AutocompleteSupportFragment向用户显示一个搜索框按钮,单击该按钮会显示一个搜索框UI
  2. 放大布局会加载UI,但您必须将其添加到视图中才能使其可见。

答案 1 :(得分:1)

使用Intent构建器代替editText中的片段。...

在Oncreate上初始化

   // Initialize Places.
   Places.initialize(getApplicationContext(), "***YOUR API KEY***");

   // Create a new Places client instance.
   PlacesClient placesClient = Places.createClient(this);

然后在点击事件中在edittext上使用以下代码...

List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME);
// Start the autocomplete intent.
Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields).build(this);
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Place place = Autocomplete.getPlaceFromIntent(data);
            Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
        } else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
            // TODO: Handle the error.
            Status status = Autocomplete.getStatusFromIntent(data);
            Log.i(TAG, status.getStatusMessage());
        } else if (resultCode == RESULT_CANCELED) {
            // The user canceled the operation.
        }
    }
}

请参考下面的链接https://stackoverflow.com/a/55045772/10579969 ...

  

如果仅使用片段,请参考以下代码

       AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
                getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
    autocompleteFragment.setCountry("IN");    //country type
    autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME)); 
   //to indicate the types of place data that you want to get.