androidandroid-fragmentsandroid-drawer

How to use Android NavigationDrawer to create other fragments?


It's my first Android project. I need to create a sliding menu to start different pages. Then I find in Android Studio 1.4 there is a default "Navigation Drawer"Activity for us to use.Here is the default image

So i want to click different items to start different fragments(i think it's fragments not activities). How can I add the code to start?

` I think I should add code here

   public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camara) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}`

Here is all the mainactivity:

package com.ad_imagine.navigationdrawer2;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class Main2Activity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main2, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camara) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

}'

Here is main layout:

<include layout="@layout/app_bar_main2" android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView android:id="@+id/nav_view"
    android:layout_width="wrap_content" android:layout_height="match_parent"
    android:layout_gravity="start" android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main2"     app:menu="@menu/activity_main2_drawer" />


Solution

  • You're on the right tracks, this is how I'm doing it (example of 1 fragment only, others are the same).

    case R.id.nav_feedback: handleFeedback();
                        break;
    

    I like to have methods that clearly show by their name what they're doing; also I try to delegate some things into private methods to keep my code cleaner. On this item clicked, we need to handle feedback, and that method looks like this:

    private void handleFeedback() {
        changeToFragment(FeedbackFragment.newInstance());
        try {
            getSupportActionBar().setTitle(R.string.feedback);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }
    

    Now there's a method called changeToFragment, should be obvious what it does:

    private void changeToFragment(Fragment fragment){
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.content_navigation_drawer, fragment)
                .commit();
    }
    

    Of course, there's a Fragment class called FeedbackFragment, and be sure that you either use android.app.Fragment and getFragmentManager or android.support.v4.app.Fragment and getSupportFragmentManager. DO NOT MIX these, otherwise you're gonna have a bad time. Refer to this question to see their differences and which one you'll wanna use. I personally opted for the one from the support library.

    I'll leave it up to you to implement the fragment classes, I hope this code was understandable for you.