我正在为我的主页导航使用一个 ActionBar,其中包含四个选项卡,指向我的应用程序中的不同区域。
其中一个区域是地图部分,其中应包含两个子选项卡以显示从 SQLite 数据库填充的项目列表。
所以基本上,我想从我的页面片段中实现嵌套导航。我到目前为止的代码是:
//MainActivity.java
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setCustomView(R.layout.rowlayout);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout layoutView = (RelativeLayout)inflater.inflate(R.layout.action_bar_tab, null);
TextView tabText = (TextView) layoutView.findViewById(R.id.tabText);
ImageView tabImage = (ImageView) layoutView.findViewById(R.id.tabImage);
String dayOneName = getResources().getString(R.string.day_one);
Tab tab = actionBar.newTab();
tab.setIcon(R.drawable.cal);
TabListener<AgendaMain> dayOne = new TabListener<AgendaMain>(this,
dayOneName, AgendaMain.class);
tab.setTabListener(dayOne);
// set custom view
tabText.setText(dayOneName);
tabImage.setImageResource(R.drawable.cal);
tab.setCustomView(layoutView);
actionBar.addTab(tab);
// Plus three more navigation tabs
private class TabListener<T extends Fragment> implements
ActionBar.TabListener {
private Fragment 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;
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(mFragment);
}
}
@Override
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
// User selected the already selected tab. Usually do nothing.
}
}
上面的选项卡链接到片段,我想在其中添加两个新选项卡,两个选项卡都显示一个 ListFragment。
我尝试从这里实现 FragmentTabHost ,但在 android.support.v4.app 和 MainActivity.java 的 TabListener 之间遇到问题。到目前为止,所有代码都在工作,只是试图将选项卡添加到片段中!
如果有人可以建议/展示实现这一点的最佳方法,将不胜感激(:到目前为止,我只设法显示静态内容,这不好!(如果需要,我将发布更多代码,我对此表示怀疑)会有所帮助,因为我没有运气!)