我正在尝试将 ActionBarSherlock 用于 android 中的选项卡视图。它只是一个带有 3 个选项卡的演示项目,每个选项卡只显示一个包含文本视图的片段。这是我的MainActivity
代码:
public class MainActivity extends SherlockFragmentActivity {
private ActionBar mActionBar;
private Tab tab1;
private Tab tab2;
private Tab tab3;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_main);
mActionBar = getSupportActionBar();
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
tab1 = mActionBar.newTab().setText("TAB1");
tab2 = mActionBar.newTab().setText("TAB2");
tab3 = mActionBar.newTab().setText("TAB3");
tab1.setTabListener(new TabSelectListener(FragmentTest
.newInstance("Fragment1"), R.id.container));
tab2.setTabListener(new TabSelectListener(FragmentTest
.newInstance("Fragment2"), R.id.container));
tab3.setTabListener(new TabSelectListener(FragmentTest
.newInstance("Fragment3"), R.id.container));
mActionBar.addTab(tab1);
mActionBar.addTab(tab2);
mActionBar.addTab(tab3);
}
private class TabSelectListener implements TabListener {
private SherlockFragment mFragment;
private int resId;
public TabSelectListener(SherlockFragment fragment, int resId) {
mFragment = fragment;
this.resId = resId;
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Log.e("Listener", "onTabSelected");
ft.replace(resId, mFragment).commit();
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Log.e("Listener", "onTabUnselected");
// ft.remove(mFragment).commit();
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Log.e("Listener", "onTabReselected");
}
}
}
//This is my FragmentTest
public class FragmentTest extends SherlockFragment {
private String name;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
TextView textView = (TextView) view.findViewById(R.id.tvText);
textView.setText("" + name);
return view;
}
public static SherlockFragment newInstance(String s) {
return new FragmentTest().setName(s);
}
public String getName() {
return name;
}
public FragmentTest setName(String name) {
this.name = name;
return this;
}
}
上面的代码将导致我的应用程序force close
出现:commit already called
错误。我搜索了很多教程,但没有任何线索。任何人都可以为我解释并修复它吗?非常感谢!