我在 fragment 中使用 PlaceAutoCompleteFragment
。第一次打开 Fragment
(其中放置了 PlaceAutoCompleteFragment
的 App fragment )时,它运行良好,就像一个魅力。但是,然后我第二次点击按钮打开 Fragment,它崩溃并出现以下错误。它只工作一次。
FATAL EXCEPTION:
android.view.InflateException: Binary XML file line #64: Error inflating class fragment
Caused by: java.lang.IllegalArgumentException: Binary XML file line #64: Duplicate id 0x7f0d0094, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.location.places.ui.PlaceAutocompleteFragment
这就是我使用它的方式:
SupportPlaceAutocompleteFragment placeAutocompleteFragment = (SupportPlaceAutocompleteFragment) getActivity().getSupportFragmentManager().
findFragmentById(R.id.place_autocomplete_fragment);
placeAutocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
System.out.println(place.getAddress());
}
@Override
public void onError(Status status) {
}
});
错误在 onCreateDialog
方法中的这一行,其中布局正在膨胀:
View view = inflater.inflate(R.layout.add_geofence_layout, null);
XML:
<fragment
android:id="@+id/place_autocomplete_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.gms.location.places.ui.SupportPlaceAutocompleteFragment" />
想知道!为什么这段代码只能运行一次?
DialogFragment 类:
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.add_geofence_layout, null);
viewHolder = new ViewHolder();
viewHolder.initializeView(view);
viewHolder.placeAutocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
System.out.println(place.getAddress());
}
@Override
public void onError(Status status) {
}
});
}
注意:- 我在 DialogFragment
中使用 PlaceautoCompleteFragment
。如果我在 Activity 中使用它,它工作正常。
不要将 PlaceAutocompleteFragment 直接添加到 fragment 布局中。您需要动态添加 PlaceAutocompleteFragment 并在 onDestroyView() 上将其删除。
layout.xml
<LinearLayout
android:id="@+id/placeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="visible">
</LinearLayout>
添加 PlaceAutocompleteFragment
PlaceAutocompleteFragment autocompleteFragment=new PlaceAutocompleteFragment();
FragmentManager fragmentManager = getActivity().getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.placeLayout,autocompleteFragment);
fragmentTransaction.commit();
在销毁时移除它
@Override
public void onDestroyView() {
super.onDestroyView();
if (getActivity() != null) {
FragmentManager fragmentManager = getActivity().getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(autocompleteFragment);
fragmentTransaction.commit();
}
我是一名优秀的程序员,十分优秀!