I have Nav Drawer, but when I launch the application, no fragment opens, therefore we see a white screen. How to make a default fragment open when opening an application?
- oneEmulate clicking on the menu - YuriySPb ♦
|
1 answer
You need to immediately call onCreate
code showing a specific fragment. To avoid duplication, it is recommended that the code responsible for displaying fragments be moved from the NavigationView
handler to the menu in a separate method.
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private NavigationView drawer; @Override protected void onCreate(Bundle savedInstanceState) { // ... drawer = (NavigationView) findViewById(R.id.navigation_drawer); drawer.setNavigationItemSelectedListener(this); selectMenuItem(R.id.fragment_1_item); } @Override public boolean onNavigationItemSelected(MenuItem menuItem) { selectMenuItem(menuItem.getItemId()); return true; } private void selectMenuItem(int index) { Fragment fragment = null; switch (index) { case R.id.fragment_1_item: fragment = new Fragment1(); break; case R.id.fragment_2_item: fragment = new Fragment2(); break; case R.id.exit_item: finish(); break; } if (fragment == null) return; FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.content_frame, fragment) .commit(); } }
Here we have a selectMenuItem
method that is responsible for handling menu items. Now you can call it in onCreate
with the desired index ( selectMenuItem(R.id.fragment_1_item)
.
|