4
\$\begingroup\$

I'm currently porting a web-based POS system to Android. The Android version uses NavigationDrawer to navigate between menus.

What I need a code review on is my current approach in loading fragments upon selected an item from navigation drawer. I'm using reflection to achieve my case.

MainActivity.java

@Override
    public void onNavigationDrawerItemSelected(String menuItemText) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        BaseFragment fragmentToOpen = null;
        Method newInstanceMethod = null;
        try {
            newInstanceMethod = AvailableMenuList.MENU_ITEM_TABLE.get(menuItemText).getMethod("newInstance", null);
            fragmentToOpen = (BaseFragment) newInstanceMethod.invoke(fragmentToOpen, null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        fragmentManager.beginTransaction()
                .replace(R.id.container, fragmentToOpen, menuItemText)
                .addToBackStack(menuItemText)
                .commit();
    }

HashMap implementation of available POS functions in Android version:

    public class AvailableMenuList {
        private AvailableMenuList() {} //Disable object instantiation

            public static final HashMap<String, Class<BaseFragment>> MENU_ITEM_TABLE = new HashMap() {{
                put("Announcement", AnnouncementListFragment.class);
                put("Board", BoardListFragment.class);
                put("SalesRegistration", SalesRegFragment.class);
                put("SalesRecords", SalesRtvFragment.class);
                put("OrderRegistration", OrderRegFragment.class);
                put("OrderRecords", OrderRtvFragment.class);
            }};
        }
    }

Is there a better approach of instantiating a new Fragment (by calling newInstance) instead of using reflection? Currently, there's only 6 functionalities but there's going to be at least 30 more in the future.

\$\endgroup\$
  • 1
    \$\begingroup\$ What version of Android are you targeting? \$\endgroup\$ – barq May 18 '15 at 7:38
  • \$\begingroup\$ @barq API Ver 10 and Up \$\endgroup\$ – l46kok May 18 '15 at 8:15
-1
\$\begingroup\$

You can use fragmentManager.findFragmentByTag() instead.

If the fragment is not found, initalize a new one.

fragment = new YourFragment();

\$\endgroup\$
  • 1
    \$\begingroup\$ It seems like the fragments are supposed to be created dynamically, i.e. they don't exist in the fragment manager already, so this is unlikely to be a good solution. \$\endgroup\$ – Simon Forsberg May 18 '15 at 12:07
  • \$\begingroup\$ Why is this a bad solution? I always do it this way. \$\endgroup\$ – barq May 18 '15 at 12:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.