我已经在活动中实现了PlaceAutocompleteFragment并且正在成功运行。但是如何在android中的片段中实现相同的?我已经像这样实现了placeautocompletefragment
PlaceAutocompleteFragment autocompleteFragment1 = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment1);
我得到的错误是
Incovertible类型;不能将'android.support.v4.app.Fragment'强制转换为com.google.android.gms.location.PlaceAutocompleteFragment'。
XML布局是
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/button_background"
card_view:cardCornerRadius="4dp"
card_view:contentPadding="0dp">
<fragment
android:id="@+id/place_autocomplete_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Place"
android:background="#fff"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
/>
</android.support.v7.widget.CardView>
提前致谢
像这样使用getActivity()
。
PlaceAutocompleteFragment autocompleteFragment1 = (PlaceAutocompleteFragment)getActivity().getFragmentManager().findFragmentById(R.id.autocomplete_fragment1);
fragment
android:id="@+id/place_autocomplete_fragment"
android:name="com.google.android.gms.location.places.ui.SupportPlaceAutocompleteFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
SupportPlaceAutocompleteFragment autocompleteFragment = (SupportPlaceAutocompleteFragment) getChildFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
您必须在XML布局文件中使用以下内容:
<fragment
android:id="@+id/place_autocomplete_fragment1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
/>
注意完整的classname和id,你的id不匹配。 (place_autocomplete_fragment1)
片段id应该是android:id="@+id/place_autocomplete_fragment1"
<fragment
android:id="@+id/place_autocomplete_fragment1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"/>
这个错误的另一个正当理由是你必须从Fragment
扩展你的android.support.v4.app.Fragment
类并将其投射到PlaceAutoCompleteFragment
,它从Fragment
扩展com.google.android.gms.location.PlaceAutocompleteFragment
类。为避免这种情况,你应该/可以使用SupportPlaceAutoCompleteFragment
而不是你正在使用。
SupportPlaceAutocompleteFragment autocompleteFragment1 = (SupportPlaceAutocompleteFragment)
getActivity.getSupportFragmentManager().findFragmentById(R.id.place_autocomplete_fragment1);
使用此功能,您的自动完成小部件也可以在较低版本的设备上运行。
这是Kotlin的解决方案。这特别适用于如果要在片段中启动自动完成片段的情况。
val autocompleteFragment = childFragmentManager.findFragmentById(R.id.autocomplete_support_fragment) as AutocompleteSupportFragment?
<fragment
android:id="@+id/autocomplete_support_fragment"
android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>