我希望在手机未连接到WiFi网络时显示另一个片段。通常我正在显示MainFragment,当没有连接可用时ErrorFragment。
我正在使用mWifi.isConnected()
检查是否存在连接。
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
if (mWifi.isConnected()) {
new PostTask(1).execute();
} else {
MainFragment.firstPageListener.onSwitchToNextFragment();
}
}
这是我的代码(在MainFragment中)切换到ErrorFragment,但它给了我
11-23 20:57:29.588: E/AndroidRuntime(4025): java.lang.IllegalStateException: Recursive entry to executePendingTransactions
这是我的MainActivity(我正在使用ViewPager):
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private final class FirstPageListener implements FirstPageFragmentListener {
public void onSwitchToNextFragment() {
mFragmentManager.beginTransaction().remove(mFragmentAtPos0).commit();
if (mFragmentAtPos0 instanceof MainFragment) {
mFragmentAtPos0 = new ErrorFragment(listener);
} else { // Instance of NextFragment
mFragmentAtPos0 = new MainFragment(listener);
}
notifyDataSetChanged();
}
}
private String[] titles = { "SEARCH", "LIST" };
private final FragmentManager mFragmentManager;
public Fragment mFragmentAtPos0;
private Context context;
FirstPageListener listener = new FirstPageListener();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
mFragmentManager = fm;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0
if (mFragmentAtPos0 == null) {
mFragmentAtPos0 = new MainFragment(listener);
}
return mFragmentAtPos0;
case 1: // Fragment # 1
return new ListFragment();
}
return null;
}
@Override
public int getCount() {
return titles.length;
}
@Override
public int getItemPosition(Object object) {
if (object instanceof MainFragment && mFragmentAtPos0 instanceof ErrorFragment) {
return POSITION_NONE;
}
if (object instanceof MainFragment && mFragmentAtPos0 instanceof MainFragment) {
return POSITION_NONE;
}
return POSITION_UNCHANGED;
}
@Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
public interface MainFragmentListener {
void onSwitchToNextFragment();
}
我尝试用以下内容更改片段:
FragmentManager fragmentManager2 = getFragmentManager();
FragmentTransaction fragmentTransaction2 = fragmentManager2.beginTransaction();
ErrorFragment fragment2 = new ErrorFragment();
fragmentTransaction2.addToBackStack("xyz");
fragmentTransaction2.hide(MainFragment.this);
fragmentTransaction2.add(android.R.id.content, fragment2);
fragmentTransaction2.commit();
但是当我滑到另一个标签时,片段重叠......应该怎么做?谢谢!
(拇指向下是ErrorFragment,按钮和开/关开关,在ListFragment中)
答案 0 :(得分:0)
尝试删除 fragmentTransaction2.hide(MainFragment.this); 并改变 fragmentTransaction2.add(android.R.id.content,fragment2); 至 fragmentTransaction2.replace(android.R.id.content,fragment2);