NOte:我已经使用ViewPager实现了标签。我正在创建一个在viewpager中有三个选项卡(Fragments)的应用程序。我想创建一个导航抽屉,在那里我可以看到这三个标签并点击任何导航我到相应的标签。
主要活动扩展了ActionBarActivity并具有以下代码
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fragment fragment = new CategoryFragment();
Bundle args = new Bundle();
args.putInt(CategoryFragment.CATEGORY_NUMBER, position);
fragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.pager, fragment);
transaction.addToBackStack(null);
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mOptionsNavDrawer[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
CategoryFragment看起来像这样
public static class CategoryFragment extends android.support.v4.app.Fragment {
public static final String CATEGORY_NUMBER = "category_number";
public CategoryFragment() {
// Empty constructor required for fragment subclasses
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int fragmentNumber = getArguments().getInt(CATEGORY_NUMBER);
View rootView=null;
if(fragmentNumber==0)
{
rootView = inflater.inflate(R.layout.F1, container, false);
}
else if (fragmentNumber==1)
{
rootView = inflater.inflate(R.layout.F2, container, false);
}
else if(fragmentNumber==2)
{
rootView = inflater.inflate(R.layout.F3, container, false);
}
else
{
rootView = inflater.inflate(R.layout.F4, container, false);
}
return rootView;
}
}
调用CategoryFragment中的OnCreateView函数,但没有设置片段(F1.F2.F3)。有没有其他方法可以调用这些片段?每个片段都是相应的标签。
答案 0 :(得分:0)
您的Activity中需要一个方法来帮助在标签之间切换。类似的东西:
public void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FragmentA();
break;
case 1:
fragment = new FragmentB();
break;
case 2:
fragment = new FragmentC();
break;
default:
break;
}
if (fragment != null) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.frame_container, fragment);
transaction.commit();
每个片段应该彼此独立,不需要将包信息传递给CategoryFragment