I have a main activity (Activity 1) which inflates a navigation drawer (with listview listing items). The drawer is run by a fragment (MenuFragment) so that I can inflate any xml layout depending on which item is selected. Now my problem is how to run another activity (Activity 2) when the user selects an item from the drawer since the drawer is run by the MenuFragment and I can start activity from a fragment. Any help is really appreciated. Thanks in advance.
3 Answers
You should never call a fragment from another fragment. Communication between fragments should be via activity.
Have a look at this other SO thread. Hope this helps.

- 1
- 1

- 311
- 2
- 7
A common pattern for this type of problem is to provide a listener interface for each fragment where the Activity needs to be notified when something within the fragment happens.
So your menu fragment could look something like:
public class MenuFragment extends Fragment
{
public interface Listener
{
void onDrawerItemSelected();
}
private Listener listener;
public void setListener(Listener listener)
{
this.listener = listener;
}
// When drawer item selected, do something like
//
// if (listener != null)
// {
// listener.onDrawerItemSelected();
// }
}
Your activity would look something like:
public class TestActivity extends Activity implements MenuFragment.Listener
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// MenuFragment fragment = ...;
// fragment.setListener(this);
}
@Override
public void onDestroy()
{
// MenuFragment fragment = ...;
// fragment.setListener(null);
super.onDestroy();
}
@Override
public void onDrawerItemSelected()
{
// TODO launch other activity here
}
}
In essence, let your Activity drive the show.

- 4,689
- 1
- 21
- 25
Use an interface
Communicating between a fragment and an activity - best practices.
You need to create an interface to your activity from your fragment. Something like:
public class MainActivity extends FragmentActivity implements MainFragment.getCommunication {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//called from the MainFragment
@Override
public void TalkToMe() {
MainFragment MainFrag = (MainFragment)getFragmentManager().findFragmentById(R.id.fragment_main);
MainFrag.MyMainFragmentMethod();
OtherFragment OtherFrag = (OtherFragment)getFragmentManager().findFragmentById(R.id.fragment_Other);
OtherFrag.MyMainFragmentMethod();
}
}
Fragment Class
public class MainFragment extends Fragment {
//interface to the MainActivity activity class
private getFragmentCommunication listener;
public interface getCommunication {
public void TalkToMe();
}
}
Here is a good article on this: http://www.vogella.com/articles/AndroidFragments/article.html.

- 1
- 1

- 7,828
- 12
- 64
- 106