onClick event in navigation drawer
Asked Answered
P

8

29

I have made a navigation drawer in Android in which I want to implement onClick for it. This is my main activity:

public class MainActivity extends AppCompatActivity {

private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle aToggle;
private Toolbar toolbar;
private RecyclerView recyclerView;
private RecyclerAdapter recyclerAdapter;
private RecyclerView.Adapter adapter;
private NavigationView navigationView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
    aToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.navig, R.string.open, R.string.Close);
    navigationView = (NavigationView) findViewById(R.id.nav_view);
    mDrawerLayout.addDrawerListener(aToggle);
    toolbar = (Toolbar) findViewById(R.id.nav_action);
    toolbar.setNavigationIcon(R.drawable.navig);
    setSupportActionBar(toolbar);
    aToggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    navigationView.setItemIconTintList(null);
    recyclerView = (RecyclerView) findViewById(R.id.recycler);
    recyclerAdapter = new RecyclerAdapter(getApplicationContext());
    RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(recyclerAdapter);


}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (aToggle.onOptionsItemSelected(item)) {
        return true;
    }
    return super.onOptionsItemSelected(item);

}}

This is my XML layout for the activity:

 <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.alpit.formula2.MainActivity">


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="0dp"
        android:orientation="vertical">

        <android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="58dp"
            android:orientation="vertical"></android.support.v7.widget.RecyclerView>

        <android.support.v7.widget.Toolbar
            android:id="@+id/nav_action"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#EF6C00"
            android:orientation="vertical"
            android:theme="@style/ThemeOverlay.AppCompat.Dark"></android.support.v7.widget.Toolbar>


    </RelativeLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#FFA726"
        app:menu="@menu/navigation_menu"
        app:theme="@style/NavigationTheme">


    </android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>

This is my menu items:

    <group
        android:id="@+id/gp1"
        android:checkableBehavior="single">
        <item
            android:id="@+id/nav_maths"
            android:icon="@drawable/maths"
            android:title="Maths" />

        <item
            android:id="@+id/nav_physics"
            android:icon="@drawable/physics"
            android:title="Physics" />

        <item
            android:id="@+id/nav_chem"
            android:icon="@drawable/chem"
            android:title="Chemistry" />

        <item
            android:id="@+id/EEE"
            android:icon="@drawable/lightbulb"
            android:title="Electronics Electrical" />
    </group>

    <group
        android:id="@+id/gp2"
        android:checkableBehavior="single">
        <item
            android:id="@+id/unitconversion"
            android:icon="@drawable/unitconversion"
            android:title="Unit Conversion" />
        <item
            android:id="@+id/Scientist"
            android:icon="@drawable/scientist"
            android:title="Scientist" />


        <item
            android:id="@+id/favourite"
            android:icon="@drawable/favourite"
            android:title="Favourite" />
    </group>

    <group
        android:id="@+id/gp3"
        android:checkableBehavior="single">
        <item
            android:id="@+id/Share"
            android:icon="@drawable/share"
            android:title="Share" />
        <item
            android:id="@+id/Rate"
            android:icon="@drawable/rate"
            android:title="Rate" />
        <item
            android:id="@+id/ads"
            android:icon="@drawable/ad"
            android:title="Remove Ads" />
        <item
            android:id="@+id/aboutus"
            android:icon="@drawable/aboutus"
            android:title="About Us" />
    </group>
</menu>

The problem is I am not able to understand how to implement the onClick on the navigation drawer as it is populated by the list given by us not by any listView.

How can I implement onClick on the items of navigation drawer?

Paramnesia answered 17/2, 2017 at 11:57 Comment(2)
as it is populated by the list given by us not by any listView could you explain what you mean by this?Nathalia
Sorry i know this line would bug, after implementing the navigationView i scanned many tutorial about them, they all were populated by a listView, by that they could easily get the location of the item clicked. Thats why i added this line.Paramnesia
D
65

You need to add implements NavigationView.OnNavigationItemSelectedListener

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener

and add method

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    // Handle navigation view item clicks here.
    switch (item.getItemId()) {

       case R.id.nav_maths: {
      //do somthing
            break;
        }  
    }
    //close navigation drawer
    mDrawerLayout.closeDrawer(GravityCompat.START);
    return true;
}

method to set Listener

private void setNavigationViewListener() {
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

call method in onCreate()

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setNavigationViewListener()
}
Darrick answered 17/2, 2017 at 12:5 Comment(4)
Can u tell how to implement onClickListner in this ?Paramnesia
It is more helpful and working fine in my project. Thanks.Oria
What if the click is actually on the header of the menu? I'm trying to capture a click on the avatar in the header and not a menu item.Disembroil
Somehow it is not calling the item selected even after added all code.Articulator
B
4

Add NavigationItemSelectedListener event to nav_view

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

Implement your Activity with NavigationView.OnNavigationItemSelectedListener

and add this code for click item

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

    if (id == R.id.nav_camera) {
        // 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;
}
Balbur answered 17/2, 2017 at 12:5 Comment(3)
I am not using framgents,so do i have to implement this method in every activity or there is any other way for it Thanks.Paramnesia
Yes you have to create navigation view and write same to for every other activity. But it is not best practice. Use fragment it will good for u to achieve ur taskBalbur
Sorry for late reply,but nothing is happening when i does it.Paramnesia
K
2

Below code is for adding toggle to DrawerLayout

 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);

And to add listener to Navigation menu items

implements NavigationView.OnNavigationItemSelectedListener

and override below method

@Override
  public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    if(id == R.id. nav_maths){
      //Handle your stuff here
    } 
}

Add below code to onCreate method

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Kariekaril answered 17/2, 2017 at 12:5 Comment(2)
Nothing is happening when i does it.Paramnesia
You have missed returning a boolean and closing the drawer.Ranger
P
2
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val nav_view: NavigationView = findViewById(R.id.nav_view)
    nav_view.setNavigationItemSelectedListener(this)
    nav_view.bringToFront();
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
    when(item.itemId){
        R.id.miid_log_out -> Toast.makeText(this, "Working", Toast.LENGTH_SHORT).show()
    }
    return false
}

}

Plectognath answered 9/2, 2021 at 11:20 Comment(0)
A
1

in your

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (aToggle.onOptionsItemSelected(item)) {
        return true;
    }
    return super.onOptionsItemSelected(item);

}}

add these lines:

switch (item.getItemId()) {
    case R.id.nav_maths:
        // your logic here.
        return true;
    case R.id.nav_physics:
        //your logic here
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
Ambition answered 17/2, 2017 at 12:9 Comment(0)
S
1

Step-1: Extends the NavigationView.OnNavigationItemSelectedListener on your Activity Step2: Then there will show an error then override the method:

  @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        return false;
    }

get the Id with menuItem.getId() .And Perform Your Action as per your need.

final Step: Add This line in onCreate navigationView.setNavigationItemSelectedListener(this);

That's it.

Septennial answered 25/9, 2019 at 8:30 Comment(0)
O
1
 binding.navigationView.setNavigationItemSelectedListener {
            when(it.itemId){
                R.id.book -> Toast.makeText(applicationContext, "Booked", Toast.LENGTH_SHORT).show()
            }
            true
        }
Ortego answered 2/4, 2021 at 11:18 Comment(1)
While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Pragmatist
P
-6
  fab=(FloatingActionButton)findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
}
    }
Product answered 19/2, 2017 at 15:50 Comment(1)
Please add some context to as why this code works. That improves the quality of your answer! :)Nearly

© 2022 - 2024 — McMap. All rights reserved.