user3383415 user3383415 - 5 months ago 31
Android Question

Navigation drawer default fragment

I am novice developer and I´m integrating Navigation drawer in my app with android-support v7 and I have one question. When I start the app the main layout is this:

<?xml version="1.0" encoding="utf-8"?>




<!-- The main content view -->

<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />

<!-- The navigation drawer -->

<ListView
android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@android:color/white"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp" />




and this is my main activity:

drawerList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {

Fragment fragment = null;

switch (position) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
case 3:
fragment = new Fragment4();
break;
}

FragmentManager fragmentManager =
getSupportFragmentManager();

fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();

drawerList.setItemChecked(position, true);

tituloSeccion = opcionesMenu[position];
getSupportActionBar().setTitle(tituloSeccion);

drawerLayout.closeDrawer(drawerList);
}
});


How can I set default fragment like main layout of the app? Thank you

Answer

If it is ok for you to load the default fragment every time your activity is created, you can put a FragmentTransaction in onCreate()

Looks something like this:

@Override
public void onCreate(Bundle savedInstanceState){

    super.onCreate(savedInstanceState);
    FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
    tx.replace(R.id.content_frame, new Fragment1());
    tx.commit();


}

If you want a more sophisticated way of doing this (for example switching to a different fragment when you go back to the main activity), you can use an Intent with extras determining the fragment in onCreate(), where you just put your default fragment in the defaultValue upon loading the extra:

int position = getIntent().getIntExtra("position", 1);
switch(position){

    ...

}