我有一个Activity,其容器是FrameLayout。我需要向该容器添加一个片段,但这样做会抛出IllegalStateException,从而破坏我的Activity。
这是我在活动布局中的容器:
PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
Bundle bundle = new Bundle();
bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
placesSeeMoreFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer,
placesSeeMoreFragment).commit();
这就是我将片段添加到活动
的方法java.lang.IllegalStateException: Activity has been destroyed
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1515)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:634)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:613)
at net.ilb.Activities.PlacesActivity.openPlaceSeeMore(PlacesActivity.java:140)
这是logcat
public void openPlaceSeeMore(int poiID){
PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
Bundle bundle = new Bundle();
bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
placesSeeMoreFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer, placesSeeMoreFragment).commit();
}
我在这里做错了什么?
编辑:
我将片段添加到公共方法的活动中,我从ListView的onItemClickListener调用该方法
这是整个方法
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
PlacesActivity placesActivity = new PlacesActivity();
placesActivity.openPlaceSeeMore(poi.getId());
}
});
这就是调用方法的方法
{{1}}
答案 0 :(得分:1)
使用以下代码......
Fragment fragment = new PlacesSeeMoreFragment();
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
Bundle bundle = new Bundle();
bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
fragment.setArguments(bundle);
答案 1 :(得分:1)
有时我遇到同样的问题,这就是我所做的。使用commitAllowingStateLoss()
代替commit()
。试试这个
getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer, placesSeeMoreFragment).commitAllowingStateLoss();
答案 2 :(得分:1)
我想你是在说这个:
PlacesActivity placesActivity = new PlacesActivity();
调用在activity中声明的方法这是一种非常错误的方法。 每次单击列表中的内容时,都会创建活动的新实例。此外,如果您想捕获列表单击,则应使用接口,而不是在任何地方使用活动对象。
希望这有帮助。
答案 3 :(得分:-1)
试试这个,
PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
Bundle bundle = new Bundle();
bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
placesSeeMoreFragment.setArguments(bundle);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.seeMoreContainer, placesSeeMoreFragment );
transaction.commit();