2017-04-05 6 views
0

私はアプリケーションを作成しており、DrawerActivityを使用しています。 このDrawerActivityには、onNavigationItemSelected()メソッドがあります。私が持っている 質問は、私はので、私は唯一の所望のフラグメントを渡すフラグメントによる動的メソッド

public void select(Fragment fragment) { 
    FragmentTransaction transaction = menuActivity.getSupportFragmentManager().beginTransaction(); 

    transaction.replace(R.id.fragment_container, fragment); 
    transaction.addToBackStack(null); 

    transaction.commit(); 
} 

のようなメソッドを作成することができ、あります。過去に私はコードの行を削除していましたが、今これを変更したいと思います。あなたが望むなら、私が作成したいと思う柔軟な方法です。上記の例は明確なオブジェクトを期待しているので機能しませんが、私の質問のポイントを得ることを願っています。あなたの注意のための

感謝:)

+0

あなたは単にonNavigationItemSelected(に送らIDに基づいて、フラグメント・インスタンスを作成)し、呼び出すことはできませんメソッドを選択しますか? – Brianvdb

+0

私はたくさんのフラグメントを持っていて、コードを減らそうとしています – ProgFroz

答えて

0

あなたが常に特定のフラグメントにすべてのメニュー項目IDをマップする必要があります。

長いスイッチケースステートメントを避けるために、Abstract Factory Patternのようなデザインパターンをリフレクションに使用できます。比べ

いくつかのサンプルコード

public class FragmentFactory { 
    private Map<Integer, Class<? extends Fragment>> menuItemFragments; 

    public FragmentFactory() { 
     menuItemFragments = new HashMap<>(); 
     menuItemFragments.put(R.id.fragment_main, MainFragment.class); 
     menuItemFragments.put(R.id.fragment_about, AboutFragment.class); 
     menuItemFragments.put(R.id.fragment_settings, SettingsFragment.class); 
    } 

    public Fragment getFragmentById(int menuItemId) { 
     Class<? extends Fragment> fragmentClass = menuItemFragments.get(menuItemId); 
     if(fragmentClass == null) throw new NullPointerException("fragment not found"); 
     try { 
      return fragmentClass.newInstance(); 
     } catch (InstantiationException | IllegalAccessException e) { 
      throw new RuntimeException("failed to construct fragment", e); 
     } 
    } 
} 

次んonNavigationItemSelected:

private FragmentFactory mFragmentFactory = new FragmentFactory(); 

public boolean onNavigationItemSelected(MenuItem menuItem) { 
     Fragment fragment = mFragmentFactory.getFragmentById(menuItem.getItemId()); 
     select(fragment); 

     return true; 
} 
+0

しかし、私はいつもハッシュマップのフラグメントの位置を知る必要がありますか? – ProgFroz

+0

これは、メニュー項目IDとマップされているため、いいえです。単にgetFragmentByIdメソッドを使用して、メニュー項目に属するフラグメントを取得します。 – Brianvdb

関連する問題