I have a trouble with my app. I want to make an app that has WebView and will change the URL when I click one of the items on the navigation drawer. For example:
Facebook
Twitter
Github
and so on. But I couldn't implement the onClick event. I am new in Android development. Thanks in advance.
This is my Java File
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private Toolbar mToolBar;
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolBar = (Toolbar) findViewById(R.id.nav_action_bar);
setSupportActionBar(mToolBar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("https://www.facebook.com/groups/276912206003690/");
webView.setWebViewClient(new WebViewClient());
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if(webView.canGoBack()){
webView.goBack();
}else{
super.onBackPressed();
}
}
}
This my Main_activity.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.tehedligmail.navigation_drawer.MainActivity"
android:id="#+id/drawer_layout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout = "#layout/navigation_action_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/webView">
</WebView>
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:menu="#menu/navigation_menu"
app:headerLayout="#layout/navigation_header"
android:layout_gravity = "start">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
This is my Menu file menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/settings"
android:icon="#mipmap/ic_launcher"
android:title="Settings" />
<item
android:id="#+id/log_out"
android:title="Log out"
android:icon="#mipmap/ic_launcher"/>
<item
android:id="#+id/google"
android:title="google"
android:icon="#mipmap/ic_launcher"/>
</menu>
Your MainActivity needs to implement NavigationView.OnNavigationItemSelectedListener and override onNavigationItemSelected
Create an instance of NavigationView(e.g. mNavigationView) and bind it to your view.
Set listener as mNavigationView.setNavigationItemSelectedListener(this);
Override onNavigationItemSelected()
Here's how that method looks:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.settings) {
//do something
} else if (id == R.id.log_out){
//do something
} else if (id == R.id.google) {
//do something
}
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
Related
I have created a DrawerLayout and it works fine. But I want it to close when the user touches the background. This can be implemented with a DrawerLayout with listView but here i'm using a NavigationView. So is there a way to accomplish this?
Here is the menu layout for the NavigationView
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/home" android:title="Home Parent" android:icon="#drawable/ic_home_black"/>
<item android:id="#+id/send" android:title="Send" android:icon="#drawable/ic_send_black"/>
<item android:id="#+id/add" android:title="Add" android:icon="#drawable/ic_add_black"/>
</menu>
Here is the java code
public class ParentActivity extends AppCompatActivity {
private NavigationView mNavigationView;
private User mCurrentUser;
private UserLocalStore mUserLocalStore;
private CircleImageView mProfilePic;
private TextView mProfileName;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parent);
mUserLocalStore = new UserLocalStore(this);
mCurrentUser = mUserLocalStore.getUserDetails();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mNavigationView = (NavigationView)findViewById(R.id.navigationView);
setNavigationViewMenu(mCurrentUser.userType);
mProfileName = (TextView) mNavigationView.getHeaderView(0).findViewById(R.id.profileName);
mProfileName.setText(mCurrentUser.getName());
mProfilePic = (CircleImageView) mNavigationView.getHeaderView(0).findViewById(R.id.circleImageProfile);
Picasso.with(this).load("https://www.sonypark360.net/wp-content/uploads/2017/08/profile-pictures.png").into(mProfilePic);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
mDrawerLayout.closeDrawers();
return false;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
private void setNavigationViewMenu(String userType) {
switch (userType){
case "s":
mNavigationView.inflateMenu(R.menu.menu_student_navigation_drawer);
break;
case "pa":
mNavigationView.inflateMenu(R.menu.menu_parent_navigation_drawer);
break;
case "pr":
mNavigationView.inflateMenu(R.menu.menu_principal_navigation_drawer);
break;
case "t":
mNavigationView.inflateMenu(R.menu.menu_teacher_navigation_drawer);
break;
}
}
}
Here is the DrawerLayout code
<?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.mlpj.www.morascorpions.ParentActivity">
<android.support.design.widget.NavigationView
android:id="#+id/navigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/navigation_header_layout"
>
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
I have also looked into this question, but it does not solve my problem
Try this
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Rect viewRect = new Rect();
mNavigationView.getGlobalVisibleRect(viewRect);
if (!viewRect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
//hide your navigation view here.
}
return super.dispatchTouchEvent(ev);;
}
I have a simple task:
Create a menu with few items which opens on a toggle action bar button.
My activity_main is:
<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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mt.gmtelandroid.MainActivity"
android:id="#+id/drawer_layout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/navigation_menu"
android:layout_gravity="start"
app:headerLayout="#layout/navigation_header"
>
</android.support.design.widget.NavigationView>
and navigation menu
<menu xmlns:android="http://schemas.android.com/apk/res/android" android:id="#+id/meni1" >
<item android:id="#+id/navhome"
android:title="Home"
android:icon="#mipmap/ic_home_black_24dp"
>
</item>
<item android:id="#+id/navtasks" android:title="Zadaci"
android:icon="#mipmap/ic_drive_eta_black_24dp"
></item>
<item android:id="#+id/navlogout" android:title="Odjava"
android:icon="#mipmap/ic_close_black_24dp">
</item>
<item android:id="#+id/myname" android:title="Moj Nalog"
android:icon="#mipmap/ic_account_circle_black_24dp">
</item>
Main activity is
public class MainActivity extends AppCompatActivity
{
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mtogle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mtogle = new ActionBarDrawerToggle(this, mDrawerLayout,R.string.open_menu, R.string.close_menu);
mDrawerLayout.addDrawerListener(mtogle);
mtogle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mtogle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
I don't know how to add a listener onMenuItemClick so I can handle what happens when a user clicks on a menu item.
I have tried adding some code to onOptionsItemSelected method, but when I was debuging it I found out that this method is only called on toggle buton click, not on menu item click!?
You have to implement the callbacks for NavigationView.OnNavigationItemSelectedListener in Activity as below,
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener
than handle click event of NavigationView like below code
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Intent i;
if (id == R.id.navhome) {
// perform your action here
} else if (id == R.id.navtasks) {
// perform your action here
} else if (id == R.id.navlogout) {
// perform your action here
}else if (id == R.id.myname) {
// perform your action here
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Try to add:
callback implements NavigationView.OnNavigationItemSelectedListener,
It will override onNavigationItemSelected(MenuItem item) {... }. You can put your click code here by item.getItemId().
I hope this helps you.
Menu Item click not working I tried various things but it won't work.
Here are my code:
Home Activity:
public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private Button mBtRequest;
private Button mBtContinue;
private ProfileFragment mProfileFragment;
private SetPreferences Setpref;
private SlideUp slideUp;
private View dim;
private View sliderView;
Toast toast;
private TextView mTvDrawerName;
private TextView mTvDrawerMobile;
private TextView mtoolbarTitle;
private String mfullName;
private String mMobile;
private SharedPreferences mSharedPreferences;
private CompositeSubscription mSubscriptions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Checking for first time launch - before calling setContentView()
Setpref = new SetPreferences(this);
if (!Setpref.IsLoggined()) {
gotoMain();
finish();
}
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
mSubscriptions = new CompositeSubscription();
initSharedPreferences();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.findViewById(R.id.toolbar_title).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(v, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
mBtRequest = (Button) findViewById(R.id.btn_request);
mBtContinue = (Button) findViewById(R.id.btn_continue);
mBtRequest.setOnClickListener(view -> slideUp());
mBtContinue.setOnClickListener(view -> checkout());
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);
sliderView = findViewById(R.id.slideView);
sliderView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (toast != null){
toast.cancel();
}
toast = Toast.makeText(HomeActivity.this, "click", Toast.LENGTH_SHORT);
toast.show();
}
});
dim = findViewById(R.id.dim);
slideUp = new SlideUpBuilder(sliderView)
.withListeners(new SlideUp.Listener.Events() {
#Override
public void onSlide(float percent) {
dim.setAlpha(1 - (percent / 100));
}
#Override
public void onVisibilityChanged(int visibility) {
if (visibility == View.GONE){
// fab.show();
}
}
})
.withStartGravity(Gravity.BOTTOM)
.withLoggingEnabled(true)
.withGesturesEnabled(true)
.withStartState(SlideUp.State.HIDDEN)
.build();
Typeface myraid_bold = Typeface.createFromAsset(getAssets(),"fonts/MyriadPro-Bold_0.otf");
Typeface myraid_semibold = Typeface.createFromAsset(getAssets(),"fonts/MyriadPro-Semibold_0.otf");
View header = navigationView.getHeaderView(0);
mTvDrawerName = (TextView) header.findViewById(R.id.nav_user_name);
mTvDrawerMobile = (TextView) header.findViewById(R.id.nav_mobile_number);
mtoolbarTitle = (TextView) findViewById(R.id.toolbar_title);
mTvDrawerName.setText(mfullName);
mTvDrawerMobile.setText(mMobile);
mTvDrawerName.setTypeface(myraid_bold);
mTvDrawerMobile.setTypeface(myraid_bold);
mtoolbarTitle.setTypeface(myraid_semibold);
mBtRequest.setTypeface(myraid_bold);
mBtContinue.setTypeface(myraid_bold);
}
private void initSharedPreferences() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mfullName = mSharedPreferences.getString(Constants.FULLNAME,"");
mMobile = mSharedPreferences.getString(Constants.MOBILE,"");
}
private void gotoProfile(){
if (mProfileFragment == null) {
mProfileFragment = new ProfileFragment();
}
getFragmentManager().beginTransaction().replace(R.id.fragmentFrame,mProfileFragment,ProfileFragment.TAG).commit();
}
private void gotoMain(){
Setpref.setIsLoggined(false);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
private void slideUp(){
slideUp.show();
}
private void checkout(){
}
#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);
}
private void logout() {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(Constants.MOBILE,"");
editor.putString(Constants.TOKEN,"");
editor.putString(Constants.FULLNAME,"");
editor.apply();
gotoMain();
}
private void showSnackBarMessage(String message) {
Snackbar.make(findViewById(R.id.drawer_layout),message,Snackbar.LENGTH_SHORT).show();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_my_addresses) {
// Handle the camera action
} else if (id == R.id.nav_my_orders) {
} else if (id == R.id.nav_refer) {
} else if (id == R.id.nav_logout) {
logout();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
activity_home_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_my_addresses"
android:icon="#drawable/ic_location_on_white_24px"
android:title="My Addresses" />
<item
android:id="#+id/nav_my_orders"
android:icon="#drawable/ic_history_white_24px"
android:title="My Orders" />
<item
android:id="#+id/nav_refer"
android:icon="#drawable/ic_record_voice_over_white_24px"
android:title="Refer & Earn" />
</group>
<group
android:id="#+id/menu_bottom"
android:checkableBehavior="none">
<item
android:id="#+id/nav_logout"
android:icon="#drawable/ic_exit_to_app_white_24px"
android:title="Logout" />
</group>
</menu>
nav_header_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="Aashish Kaushik"
android:id="#+id/nav_user_name"
android:textColor="#android:color/white"/>
<TextView
android:id="#+id/nav_mobile_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9910454530"
android:textColor="#android:color/white"/>
</LinearLayout>
activity_home.xml
<?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_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<FrameLayout
android:alpha="0"
android:id="#+id/dim"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/dimBg" />
<include
layout="#layout/app_bar_main"
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_main"
app:menu="#menu/activity_home_drawer" />
<!-- The Fragment -->
<FrameLayout
android:id="#+id/fragmentFrame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.DrawerLayout>
When I try to view activity_home.xml as a design it will not showing left drawer but when I install the app on device it will show the left drawer on click but when I click on any time it will not showing check able box and not working.
Update These lines of code works for me.. after update clean and rebuild Project.
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.bringToFront();
Here is a simple solution to address this issue. You can just link your HomeActivity methods to the menu items (whichever you want to). Now just create your methods and go to the menu layout. In the menu layout just add the android:onClick inside the item tag and put the particular method name inside it. And you are done. Let me know if this was useful.
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?
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()
}
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;
}
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
}
}
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);
}
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);
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.
binding.navigationView.setNavigationItemSelectedListener {
when(it.itemId){
R.id.book -> Toast.makeText(applicationContext, "Booked", Toast.LENGTH_SHORT).show()
}
true
}
fab=(FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
}
I have this menu layout "navigation_menu.xml":
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/item1"
android:title="#string/item1"/>
<item
android:id="#+id/item2"
android:title="#string/item2"/>
<item
android:id="#+id/item3"
android:title="#string/item3"/>
</menu>
My main activity layout "activity_main.xml" is this:
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity">
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/navigation_menu"
android:layout_gravity="start">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
And this is the Java code of the main activity where I initialize the drawer:
private DrawerLayout drawer_layout;
private ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
drawer_layout = (DrawerLayout)findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawer_layout, R
.string.open_drawer, R.string.close_drawer);
drawer_layout.addDrawerListener(toggle);
toggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ...
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (toggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
The drawer opens and closes correctly, but I don't know how to do something when an item is clicked, for example showing a log.
Does anyone know?
Thanks
Use onNavigationItemSelected() method to handle Navigation Drawer Item Click. See Below Code.
private NavigationView mNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// ...
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mNavigationView.setNavigationItemSelectedListener(this);// you need to set Listener.
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item)
{
// mDrawer.closeDrawer(GravityCompat.START);
switch (item.getItemId()) {
case R.id.item1: {
}
break;
case R.id.item2: {
}
break;
case R.id.item3: {
}
break;
}
return true;
}