0

嗨,我想让两个项目具有自定义布局,另一个保留初始布局。我的问题是有更好的方法,然后为每个项目使用片段。

我的代码看起来像这样

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();
        }
4

1 回答 1

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();
于 2012-08-14T21:39:42.573 回答