Search code examples
androidandroid-side-navigation

How to access navigate to side navigation menu items(Fragments) programatically?


I'm trying to access the side navigation drawer items from the code as a response to click event from other fragment items in the side navigation drawer.

Google hasn't helped so far.

EDIT : Further Elaboration

Eg: I have a button in first fragment of side nav bar. I'm trying to access the second fragment of side nav bar inside the onclick event of the button.


Solution

  • You could specify the items when you set adapter. Based upon the item clicked by the user selectItem() is called and an item at position "position" is selected. Index of first item is zero.

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mDrawerListView = (ListView) inflater.inflate(
                R.layout.fragment_navigation_drawer, container, false);
        mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectItem(position);
            }
        });
    
        mDrawerListView.setAdapter(new ArrayAdapter<String>(
                getActionBar().getThemedContext(),
                android.R.layout.simple_list_item_activated_1,
                android.R.id.text1,
                str[]));
        mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
        return mDrawerListView;
    }
    

    Later you could also get position of the item from following function.

    private void selectItem(int position) {
        mCurrentSelectedPosition = position;
    
        MainActivity.EXT_POSITION = position;
    
        if (mDrawerListView != null) {
            mDrawerListView.setItemChecked(position, true);
        }
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(mFragmentContainerView);
        }
        if (mCallbacks != null) {
            mCallbacks.onNavigationDrawerItemSelected(position);
        }
    }
    

    If you like to call different fragments based upon the position, then that could be done from your activity by using the position of the navigation drawer item.

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, MainFragment.newInstance(position + 1))
                .commit();
    }
    

    I hope this helps in some way. It would be better if you elaborate your questions or put some approach you are trying with the code.