我正在尝试在我的应用程序中实现一个 ActionBar。我的代码很好,但是当我尝试加载项目时,它给了我这个错误:
原因:java.lang.IllegalStateException:操作栏选项卡必须有回调,并强制关闭
如何实现回调?
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
public class MainResource extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tabA = actionBar.newTab();
tabA.setText("Tab A");
tabA.setTabListener(new TabListener<Categories>(this, "Tag A", Categories.class));
actionBar.addTab(tabA);
Tab tabB = actionBar.newTab();
tabB.setText("Tab B");
tabB.setTabListener(new TabListener<Favourites>(this, "Tag B", Favourites.class));
actionBar.addTab(tabB);
Tab tabC = actionBar.newTab();
tabC.setText("Tab C");
tabC.setTabListener(new TabListener<ThisWeek>(this, "Tag C", ThisWeek.class));
actionBar.addTab(tabC);
Tab tabD = actionBar.newTab();
tabC.setText("Tab D");
tabC.setTabListener(new TabListener<Estore>(this, "Tag D", Estore.class));
actionBar.addTab(tabD);
if (savedInstanceState != null) {
int savedIndex = savedInstanceState.getInt("SAVED_INDEX");
getActionBar().setSelectedNavigationItem(savedIndex);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
outState.putInt("SAVED_INDEX", getActionBar().getSelectedNavigationIndex());
}
public static class TabListener<T extends Fragment> implements ActionBar.TabListener{
private final Activity myActivity;
private final String myTag;
private final Class<T> myClass;
public TabListener(Activity activity, String tag, Class<T> cls) {
myActivity = activity;
myTag = tag;
myClass = cls;
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);
// Check if the fragment is already initialized
if (myFragment == null) {
// If not, instantiate and add it to the activity
myFragment = Fragment.instantiate(myActivity, myClass.getName());
ft.add(android.R.id.content, myFragment, myTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(myFragment);
}
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);
if (myFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(myFragment);
}
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
}