我有一个包含ViewPager的Activity。有一个按钮,允许用户在同一活动的2个布局之间切换。 一切正常,但ViewPager除外,一旦布局更新,它就不显示任何内容。我需要退出重新打开活动以查看其内容。
private void updateLayout() {
setContentView(getLayoutId());
this.viewPager = (ViewPager)findViewById(R.id.viewPager);
this.viewPagerAdapter = new MyViewPagerAdapter(this, getSupportFragmentManager(), getLayoutId());
this.viewPager.setAdapter(this.viewPagerAdapter);
this.viewPager.setCurrentItem(0);
}
public class MyViewPagerAdapter extends FragmentPagerAdapter {
...
@Override
public CharSequence getPageTitle(int position) {
return TAG + "_" + this.layoutId + "_" + position;
}
...
}
我尝试添加一些代码来删除现有的片段,但它没有帮助:
final List<Fragment> fragments = getSupportFragmentManager().getFragments();
if (fragments != null) {
//getSupportFragmentManager().getFragments().clear();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
for (final Fragment fragment : fragments) {
try {
//You can perform additional check to remove some (not all) fragments:
if (fragment instanceof MyViewPagerAdapter) {
ft.remove(fragment);
}
} catch (final Exception e) {
Crashlytics.logException(e);
}
}
ft.commitAllowingStateLoss();
}
关于如何实现这一点的任何想法?