我想要一个程序应该包含一个带有4个标签的视图,每个标签都有不同的东西(例如:1°标签=地图,2°标签=文字等等)。我对这些项目有点新意,而且我已经成功导入并使用地图启动了应用程序。如果您认为使用除Tabs以外的其他内容更好,我同意您的意见,因为我找不到任何相关信息。
答案 0 :(得分:1)
如果你有任何超过三个标签的东西,导航标签可能不是一个理想的选择。
您可以尝试sideNavigationMenu或其他一些滑动菜单库。我发现如果你刚刚开始,sideNavigationMenu是最容易使用的库。
无论如何,如果您想继续使用导航标签,下面是一些帮助您入门的示例代码。
public class MainActivity extends Activity{
public static Context appContext;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appContext = getApplicationContext();
//ActionBar
ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.addTab(bar.newTab()
.setText("Map Fragment")
.setTabListener(new TabListener<MapSampleFragment>(
this, "map_fragment", MapSampleFragment.class)));
bar.addTab(bar.newTab()
.setText("List Fragment")
.setTabListener(new TabListener<LocationListFragment>(
this, "list_fragment", LocationListFragment.class)));
bar.addTab(bar.newTab()
.setText("Other Fragment")
.setTabListener(new TabListener<MoreStuffFragment>(
this, "more_stuff_fragment", MoreStuffFragment.class)));
}
然后,您需要编写TabListener来处理片段之间的切换。由于您正在使用Google Maps Android,因此最好隐藏您的碎片并在需要时显示它们,而不是分离和附加碎片。
这几乎是从API演示中获取的代码,但使用.show()和.hide()
除外public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
private final Bundle mArgs;
private Fragment mFragment;
public TabListener(Activity activity, String tag, Class<T> clz) {
this(activity, tag, clz, null);
}
public TabListener(Activity activity, String tag, Class<T> clz, Bundle args) {
mActivity = activity;
mTag = tag;
mClass = clz;
mArgs = args;
// 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 = mActivity.getFragmentManager().findFragmentByTag(mTag);
if (mFragment != null && !mFragment.isDetached()) {
FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction();
ft.hide(mFragment);
ft.commit();
}
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (mFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
ft.add(android.R.id.content, mFragment, mTag);
} else {
ft.show(mFragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
ft.hide(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT).show();
}
}