0

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.

RmK
  • 1,408
  • 15
  • 28

1 Answers1

1

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.

Sujit Devkar
  • 1,195
  • 3
  • 12
  • 22
  • Your selectItem method gave me a good direction to think about. So I defined that method in the activity. Did a cast of the activity in the fragment (just in case), checked if getActivity() was instance of the main activity, and then called the selectItem method, passing in the position of the item. – RmK Apr 16 '15 at 17:47
  • great that I could help. :) – Sujit Devkar Apr 17 '15 at 05:56