我使用的是sherlock bar(http://actionbarsherlock.com/)。有TabListener的代码:
public class TabListener implements ActionBar.TabListener {
private String mTag;
private Fragment mFragment;
public TabListener(String tag) {
mTag = tag;
// Check to see if we already have a fragment for this tab, probably
// from a previously saved state. If so, deactivate it, because our
// initial state is that a tab isn't shown.
mFragment = getSupportFragmentManager().findFragmentByTag(mTag);
if (mFragment != null && !mFragment.isDetached()) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(mFragment);
ft.commit();
}
}
public void onTabSelected(Tab tab) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (mFragment == null) {
if((tab.getPosition()==0) || (tab.getPosition()==1)) {
mFragment = new MainListFragment(ctx, ONLINE_TYPE);
} else {
mFragment = new SimpleFragmentf();
}
ft.add(com.lib.reader.R.id.root2, mFragment, mTag);
ft.addToBackStack(null);
ft.commit();
} else {
ft.attach(mFragment);
ft.commit();
}
}
public void onTabUnselected(Tab tab) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(mFragment);
ft.commit();
}
@Override
public void onTabReselected(Tab tab) {
//To change body of implemented methods use File | Settings | File Templates.
}
}
View的部分代码:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LinearLayout v = (LinearLayout)inflater.inflate(R.layout.main, container, false);
v.addView(pager);
return v;
}
一切正常,但是当我第二次选择任何标签时 - 我收到错误:
The specified child already has a parent. You must call removeView() on the child's parent first.
我认为,附加功能中的错误,但是如何解决这个问题?
答案 0 :(得分:0)
您无法像这样向viewpager添加视图。例如,检查Jake Wharton的演示以正确实现viewpagers。