0

こんにちは、CustomLayout を持つ 2 つのアイテムを作成し、initialLayout を保持するもう 1 つのアイテムを作成したいと考えています。私の質問は、すべてのアイテムにフラグメントを使用するよりも良い方法があるということです。

私のコードは次のようになります

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 に答える