PlaceAutocompleteFragment.setOnPlaceSelectedListener不在片段内部触发

时间:2018-09-16 10:54:28

标签: android android-studio google-places-api googleplacesautocomplete

我在map_fragment类中使用SupportPlaceAutoCompleteFragment作为嵌套片段。首先,我动态初始化SupportPlaceAutoCompleteFragment并在销毁时将其删除。但PlaceAutocompleteFragmentset.OnPlaceSelectedListener方法无效。

下面是我的代码。

初始化场所片段:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.where_to_refuel_frag, container, false);

        autocompleteFragment = new SupportPlaceAutocompleteFragment();
        android.support.v4.app.FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.fragment_content, autocompleteFragment);
        ft.commit();

        autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
            @Override
            public void onPlaceSelected(Place place) {
                // TODO: Get info about the selected place.
                Log.i(TAG, "Place: " + place.getName());
                Toast.makeText(getActivity(), place.getName(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(Status status) {
                // TODO: Handle the error.
                Log.i(TAG, "An error occurred: " + status);
            }
            });
return rootView;
}

xml中的frame_layout:

<FrameLayout
        android:id="@+id/fragment_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

OnDestroy方法:

@Override
    public void onDestroyView() {
        if (autocompleteFragment != null) {
            android.support.v4.app.FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
            fragmentTransaction.remove(autocompleteFragment).commitNowAllowingStateLoss();
        }
        super.onDestroyView();
    }

OnActivityResult:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        autocompleteFragment.onActivityResult(requestCode, resultCode, data);
    }

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

在我的情况下,我使用了依赖项: com.google.android.gms:play-services-places:15.0.1 和 com.google.android.gms:play-services-location:15.0.1

然后我进行了导入,并且可以正常工作。