我有一个使用 TabBarSherlock 和 Support 库构建的应用程序,用于将 ActionBar 支持添加到 3.0 之前的设备。我不记得我遵循什么教程来创建选项卡和侦听器,但我有以下代码。
首先创建选项卡(在 SherlockFragmentActivity 内):
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
/*--------Setup News Tab--------*/
Tab tab1 = actionBar.newTab()
.setText("News")
.setTabListener(new TabListener<TabFragment>(
this, "tab1", TabFragment.class));
Bundle newsBundle = new Bundle();
newsBundle.putInt("news_id", newsID);
tab1.setTag(newsBundle);
actionBar.addTab(tab1);
/*------------------------------*/
// This is repeated 3 more times to total 4 Tabs.
然后我有一个 classCalled TabListener
,在每个选项卡中使用它来检测它们何时被选中。
public class TabListener<T extends Fragment> implements ActionBar.TabListener{
private TabFragment mFragment;
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
public TabListener(Activity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialised
if (mFragment == null) {
Log.v("FRAGMENT", "FRAGMENT NEEDS TO BE CREATED");
mFragment = (TabFragment) Fragment.instantiate(mActivity, mClass.getName(), (Bundle)tab.getTag());
ft.add(android.R.id.content, mFragment, mTag);
} else {
Log.v("FRAGMENT", "FRAGMENT ALREADY CREATED");
ft.show(mFragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
ft.hide(mFragment);
}
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
与TabFragment
包含ViewPager
每个选项卡的类。My issue is that when selecting a Tab other than the first one the content inside the Fragment does not show. 从片段初始化时的日志中,我可以看出正在创建视图,只是没有显示,它只是一个显示背景的空白区域。