每个导航项的自定义布局

时间:2012-08-14 21:15:25

标签: android navigation android-actionbar selected

您好我想制作两个具有CustomLayout的项目,另一个保留initialLayout。我的问题是有更好的方法来为每个项目使用片段。

我的代码看起来像这样

if(actionBar.getSelectedNavigationIndex() == 0){

            android.app.FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            TimePickerFragment timePickerFragment = new TimePickerFragment();
            fragmentTransaction.add(R.id.container, timePickerFragment);
            fragmentTransaction.commit();
        } else if(actionBar.getSelectedNavigationIndex() == 1)
            android.app.FragmentManager fragmentManager1 = getFragmentManager();
            FragmentTransaction fragmentTransaction1 = fragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.container, initialFragment);
            fragmentTransaction.commit();
        } else if(actionBar.getSelectedNavigationIndex() == 2)
            android.app.FragmentManager fragmentManager2 = getFragmentManager();
            FragmentTransaction fragmentTransaction2 = fragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.container, initialFragment);
            fragmentTransaction.commit();
        } else if(actionBar.getSelectedNavigationIndex() == 3)
            android.app.FragmentManager fragmentManager3 = getFragmentManager();
            FragmentTransaction fragmentTransaction3 = fragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.container, initialFragment);
            fragmentTransaction.commit();
        }  else if(actionBar.getSelectedNavigationIndex() == 4)
            android.app.FragmentManager fragmentManager4 = getFragmentManager();
            FragmentTransaction fragmentTransaction4 = fragmentManager.beginTransaction();
            DatePickerFragment datePickerFragment = new DatePickerFragment();
            fragmentTransaction.add(R.id.container, datePickerFragmen);
            fragmentTransaction.commit();
        }  else if(actionBar.getSelectedNavigationIndex() == 5)
            android.app.FragmentManager fragmentManager5 = getFragmentManager();
            FragmentTransaction fragmentTransaction5 = fragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.container, initialFragment);
            fragmentTransaction.commit();
        }

1 个答案:

答案 0 :(得分:0)

你没有注意到你有6次重复代码吗?

android.app.FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
TimePickerFragment timePickerFragment = new TimePickerFragment();
fragmentTransaction.add(R.id.container, /* Put here fragment variable generated by your defined conditions */);
fragmentTransaction.commit();