Switching Fragments in navigation drawer using onNavigationItemSelected()

Vipul Behl

So I have gone through many answers on StackOverFlow but could not get this working. I want to switch fragments on navigation drawer item click. I am using the default navigation drawer in Android Studio 1.5.

I followed this answer, i have made sure that i have all my fragments created. The problem is whenever i click on any menu item the app stops working. Here's what I have till now.

MainActivity.java

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
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 MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        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);

        displayView(R.id.twitter);
    }

    @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.main, 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.
        displayView(item.getItemId());
        return true;
    }

    public void displayView(int viewId) {

        Fragment fragment = null;
        String title = getString(R.string.app_name);

        switch (viewId) {
            case R.id.facebook:
                fragment = new FacebookFragment();
                title = "Facebook";
                break;
            case R.id.twitter:
                fragment = new TwitterFragment();
                title = "Twitter";
                break;
            case R.id.googleplus:
                fragment = new GooglePlusFragment();
                title = "Google Plus";
                break;
            case R.id.settings:
                fragment = new SettingsFragment();
                title = "Settings";
                break;
        }

        if (fragment != null) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.content_frame, fragment);
            ft.commit();
        }

        // set the toolbar title
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(title);
        }

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

    }
}

FacebookFragment.java

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link FacebookFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link FacebookFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FacebookFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public FacebookFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FacebookFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FacebookFragment newInstance(String param1, String param2) {
        FacebookFragment fragment = new FacebookFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_facebook, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

I have added FrameLayout to content_main.xml file as it was suggested in the question i referred to. Any help is appreciated.

W0rmH0le

By your logcat, error is:

com.internetwarz.sploon.MainActivity@3caae0bc must implement OnFragmentInteractionListener

I think the error happened because your parent activity (MainActivity.java) did not implement this method: OnFragmentInteractionListener

You can see by the comments:

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

So, the solution would be:

public class MainActivity extends AppCompatActivity 
    implements NavigationView.OnNavigationItemSelectedListener,
               FacebookFragment.OnFragmentInteractionListener {

    ....

    // Add the method below to MainActivity.java
    private void onFragmentInteraction(Uri uri) {
        // Do something or just return
        Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

Switching between Android Navigation Drawer image and Up caret when using fragments

From Dev

How to change fragments using Android navigation drawer

From Dev

Navigation Drawer to switch activities instead of fragments

From Dev

Load navigation drawer slider with Dynamic Fragments

From Dev

Android - Navigation drawer fragments

From Dev

Navigation Drawer implies nested fragments?

From Dev

Android Navigation Drawer with many fragments

From Dev

Navigation drawer with Activity and child Fragments

From Dev

Android - How to change fragments in the Navigation Drawer

From Dev

Fragments are not loaded from Navigation Drawer Click Listener

From Dev

Android save Fragments into Navigation Drawer

From Dev

Type error - Switch fragments in the Navigation Drawer

From Dev

Short black flashs when switching fragments in navigation drawer

From Dev

Switching fragments in navigation drawer

From Dev

Switch between Fragments with onNavigationItemSelected in new Navigation Drawer Activity template (Android Studio 1.4 onward)

From Dev

how to avoid Fragments Overlap in android with Navigation Drawer

From Dev

Drawer NavigationView + Fragments with viewpager, how to avoid caching data when switching fragments in navigation drawer from one to another?

From Dev

Different toolbar for fragments and Navigation Drawer

From Dev

Set Fragments with TabLayout and Navigation Drawer

From Dev

Setting navigation drawer on top of other fragments

From Dev

Android - Navigation drawer fragments

From Dev

Navigation drawer with Activity and child Fragments

From Dev

Image above Navigation Drawer (using fragments)

From Dev

Switching fragments in navigation drawer

From Dev

Navigation Drawer Fragments

From Dev

navigation drawer move between fragments

From Dev

How to save state with navigation drawer and fragments

From Dev

Fragments not showing using navigation drawer

From Dev

What are the advantages of using Navigation Drawer with Activities VS with Fragments?

Related Related

  1. 1

    Switching between Android Navigation Drawer image and Up caret when using fragments

  2. 2

    How to change fragments using Android navigation drawer

  3. 3

    Navigation Drawer to switch activities instead of fragments

  4. 4

    Load navigation drawer slider with Dynamic Fragments

  5. 5

    Android - Navigation drawer fragments

  6. 6

    Navigation Drawer implies nested fragments?

  7. 7

    Android Navigation Drawer with many fragments

  8. 8

    Navigation drawer with Activity and child Fragments

  9. 9

    Android - How to change fragments in the Navigation Drawer

  10. 10

    Fragments are not loaded from Navigation Drawer Click Listener

  11. 11

    Android save Fragments into Navigation Drawer

  12. 12

    Type error - Switch fragments in the Navigation Drawer

  13. 13

    Short black flashs when switching fragments in navigation drawer

  14. 14

    Switching fragments in navigation drawer

  15. 15

    Switch between Fragments with onNavigationItemSelected in new Navigation Drawer Activity template (Android Studio 1.4 onward)

  16. 16

    how to avoid Fragments Overlap in android with Navigation Drawer

  17. 17

    Drawer NavigationView + Fragments with viewpager, how to avoid caching data when switching fragments in navigation drawer from one to another?

  18. 18

    Different toolbar for fragments and Navigation Drawer

  19. 19

    Set Fragments with TabLayout and Navigation Drawer

  20. 20

    Setting navigation drawer on top of other fragments

  21. 21

    Android - Navigation drawer fragments

  22. 22

    Navigation drawer with Activity and child Fragments

  23. 23

    Image above Navigation Drawer (using fragments)

  24. 24

    Switching fragments in navigation drawer

  25. 25

    Navigation Drawer Fragments

  26. 26

    navigation drawer move between fragments

  27. 27

    How to save state with navigation drawer and fragments

  28. 28

    Fragments not showing using navigation drawer

  29. 29

    What are the advantages of using Navigation Drawer with Activities VS with Fragments?

HotTag

Archive