This question already has answers here:
Navigation Drawer closes on click
(1 answer)
Sliding navigation drawer not handling clicks on menu items android
(3 answers)
How to fix Android studio 3.5 navigation activity template onNavigationItemSelected not working
(5 answers)
Closed 3 years ago.
I am trying to set up a Navigation Activity in my application. The problem is that I cannot switch between the Menu fragments. It looks like the menu items are not clickable.
I tried to set up the Navigation Activity in the same way I have already set up a menu (Action Bar) before but it's just not working. Also with on Click Listener, the items don't react.
My question is now on how to make the onNavigationItemSelected() method work?
Sorry for the mass of code.
public class NavActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = 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 = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, R.id.nav_send)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nav, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home: {
Toast.makeText(NavActivity.this, "Anmeldung Fehlgeschlagen", Toast.LENGTH_LONG).show();
return true;
}
case R.id.nav_gallery:
// User chose the "Favorite" action, mark the current item
// as a favorite...
return true;
}
return super.onOptionsItemSelected(item);
}
app_bar_nav.xml
<androidx.coordinatorlayout.widget.CoordinatorLayout 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=".NavActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:clickable="true"
app:srcCompat="#android:drawable/ic_dialog_email" />
<include layout="#layout/content_nav" />
activity_nav_drawer.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:App="http://schemas.android.com/apk/res-auto"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_menu_camera"
android:title="#string/menu_home"
android:clickable="true"/>
<item
android:id="#+id/nav_gallery"
android:icon="#drawable/ic_menu_gallery"
android:title="#string/menu_gallery"
android:clickable="true"/>
<item
android:id="#+id/nav_slideshow"
android:icon="#drawable/ic_menu_slideshow"
android:title="#string/menu_slideshow"
App:showAsAction="always"
android:clickable="true"/>
<item
android:id="#+id/nav_tools"
android:icon="#drawable/ic_menu_manage"
android:title="#string/menu_tools"
android:clickable="true"/>
</group>
<item android:title="Communicate">
<menu>
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_menu_share"
android:title="#string/menu_share"
android:clickable="true"/>
<item
android:id="#+id/nav_send"
android:icon="#drawable/ic_menu_send"
android:title="#string/menu_send"
android:clickable="true"/>
</menu>
</item>
mobile_navigation.xml
<navigation 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/mobile_navigation"
app:startDestination="#+id/nav_home">
<fragment
android:id="#+id/nav_home"
android:name="com.example.login.ui.home.HomeFragment"
android:label="#string/menu_home"
tools:layout="#layout/fragment_home"
android:clickable="true"/>
<fragment
android:id="#+id/nav_gallery"
android:name="com.example.login.ui.gallery.GalleryFragment"
android:label="#string/menu_gallery"
tools:layout="#layout/fragment_gallery" />
<fragment
android:id="#+id/nav_slideshow"
android:name="com.example.login.ui.slideshow.SlideshowFragment"
android:label="#string/menu_slideshow"
tools:layout="#layout/fragment_slideshow" />
<fragment
android:id="#+id/nav_tools"
android:name="com.example.login.ui.tools.ToolsFragment"
android:label="#string/menu_tools"
tools:layout="#layout/fragment_tools" />
<fragment
android:id="#+id/nav_share"
android:name="com.example.login.ui.share.ShareFragment"
android:label="#string/menu_share"
tools:layout="#layout/fragment_share" />
<fragment
android:id="#+id/nav_send"
android:name="com.example.login.ui.send.SendFragment"
android:label="#string/menu_send"
tools:layout="#layout/fragment_send" />
acitivty_nav.xml
<androidx.drawerlayout.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">
<com.google.android.material.navigation.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_nav"
app:menu="#menu/activity_nav_drawer" />
<include
layout="#layout/app_bar_nav"
android:layout_width="match_parent"
android:layout_height="match_parent" />
I have updated my answer please check I have added listener
public class NavActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = 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 = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, R.id.nav_send)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nav, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home: {
Toast.makeText(NavActivity.this, "Anmeldung Fehlgeschlagen", Toast.LENGTH_LONG).show();
return true;
}
case R.id.nav_gallery:
// User chose the "Favorite" action, mark the current item
// as a favorite...
return true;
}
return super.onOptionsItemSelected(item);
}
Related
How can I open New Activity by clicking a Navigation Drawer Menu Item?
Share_Home.java
public class Share_Home extends AppCompatActivity {
private long backPressedTime;
private ActionBarDrawerToggle toggle;
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share_home);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
tabs.setTabMode(TabLayout.MODE_SCROLLABLE);
tabs.getTabAt(1).select();
toggle = new ActionBarDrawerToggle(this, drawer, R.string.open, R.string.close);
drawer.addDrawerListener(toggle);
toggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (toggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_share_home.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.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/nav_menu_item" />
<include
layout="#layout/activity_tabs_menu"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.drawerlayout.widget.DrawerLayout>
nav_menu_item.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/nav_Setting"
android:icon="#drawable/setting_icon"
android:title="#string/nav_Setting" />
<item
android:id="#+id/nav_Help"
android:icon="#drawable/help_icon"
android:title="#string/nav_Help" />
<item
android:id="#+id/nav_Ratings"
android:icon="#drawable/rating_icon"
android:title="#string/nav_Ratings" />
<item
android:id="#+id/nav_About"
android:icon="#drawable/about_icon"
android:title="#string/nav_About" />
</menu>
Set a NavigationItemSelectedListener to you NavigationView:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id=menuItem.getItemId();
if (id == R.id.xxx){
Intent newIntent = new Intent(this, NewActivity.class);
startActivity(newIntent);
}
return true;
}
});
Also change your layout.
Instead of:
<androidx.drawerlayout.widget.DrawerLayout >
<include layout="#layout/app_bar_main" />
<com.google.android.material.navigation.NavigationView/>
<include layout="#layout/activity_tabs_menu"/>
</androidx.drawerlayout.widget.DrawerLayout>
Use:
<androidx.drawerlayout.widget.DrawerLayout >
<include layout="#layout/app_bar_main" />
<com.google.android.material.navigation.NavigationView/>
</androidx.drawerlayout.widget.DrawerLayout>
moving the <include layout="#layout/activity_tabs_menu"/> inside the app_bar_main layout.
You have to override onNavigationItemSelected and check the id of the selected menu item and then open Activity:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.activity1:
startActivity(new Intent(this, Activity1.class));
break;
case R.id.activity2:
startActivity(new Intent(this, Activity2.class));
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
And remember to add id to every item in menu layout:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/activity1"
android:title="#string/activity1" />
<item
android:id="#+id/activity2"
android:title="#string/activity2" />
</menu>
Here is how you can do it:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
final int itemId = item.getItemId();
if (itemId == R.id.nav_Setting) {
Intent newIntent = new Intent(getApplicationContext(), YourSettingActivity.class);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(newIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.nav_menu_item, menu);
return super.onCreateOptionsMenu(menu);
}
You get a listener in your NavigationView that listens to the item pressed. So you can set the listener and then start an activity when a particular item is pressed in the NavigationDrawer, like so:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.menu_item_1:
Intent intent = new Intent(this, ItemActivity.class);
startActivity(intent);
break;
}
}
});
on my activity_main_drawer i got many items but i don't know what code and where it goes to add for switching fragment
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_contests"
android:icon="#drawable/ic_menu_camera"
android:title="#string/menu_home" />
<item
android:id="#+id/nav_rules"
android:icon="#drawable/irules"
android:title="#string/box_contest_rules" />
<item
android:id="#+id/nav_profile"
android:icon="#drawable/ic_baseline_face_24"
android:title="#string/profile_page" />
<item
android:id="#+id/nav_calendar"
android:icon="#drawable/icalendar"
android:title="#string/calendar_page" />
<item
android:id="#+id/nav_gallery"
android:icon="#drawable/igallery"
android:title="#string/gallery_page" />
<item
android:id="#+id/nav_stats"
android:icon="#drawable/istats"
android:title="#string/stats_page" />
<item
android:id="#+id/nav_rank"
android:icon="#drawable/irank"
android:title="#string/rank_page" />
<item
android:id="#+id/nav_shop"
android:icon="#drawable/ishop"
android:title="#string/shop_page" />
<item
android:id="#+id/nav_setting"
android:icon="#drawable/ic_baseline_settings_24"
android:title="#string/setting_page" />
</group>
</menu>
this is the java HomePage where i am struggling to understand where and what code to add
public class HomePage extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_page, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
and this is one of the fragment java as example.
public class GalleryFragment extends Fragment {
private GalleryViewModel galleryViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
galleryViewModel =
ViewModelProviders.of(this).get(GalleryViewModel.class);
View root = inflater.inflate(R.layout.fragment_gallery, container, false);
final TextView textView = root.findViewById(R.id.text_gallery);
galleryViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
it would be great as example to switch from HomePage to GalleryFragment and back
try-->
put this in your mainactivity:-
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_contests) {
//intent to next activity
} else if (id == R.id.nav_rules) {
//just an example
String message = "Text I want to share.";
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(share, "Title of the dialog the system will open"));
} else if (id == R.id.nav_profile) {
///your actions
}
} else if (id == R.id.nav_calendar) {
}
} else if (id == R.id.nav_gallery) {
}
} else if (id == R.id.nav_stats) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Demo
main_activity:
package ijsolutions.appnav;
import android.os.Bundle;
import androidx.core.view.GravityCompat;
import androidx.appcompat.app.ActionBarDrawerToggle;
import android.view.MenuItem;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.view.Menu;
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);
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);
//add this line to display menu1 when the activity is loaded
displaySelectedScreen(R.id.nav_home);
}
#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 displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_home:
fragment = new Menu1();
//ft.addToBackStack(null);
break;
case R.id.nav_gallery:
fragment = new Menu2();
ft.addToBackStack(null);
break;
case R.id.nav_slideshow:
fragment = new Menu3();
ft.addToBackStack(null);
break;
}
//replacing the fragment
if (fragment != null) {
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
//calling the method displayselectedscreen and passing the id of selected menu
displaySelectedScreen(item.getItemId());
//make this method blank
return true;
}}
Menu1
public class Menu1 extends Fragment {
public Menu1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_menu1, container, false);
}
}
xml of menu1
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:context=".Menu1"
android:background="#68a">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/Home"
android:layout_marginLeft="60dp"
android:textSize="50dp"
/>
so am not puting the rest menus as it is same
activitymain xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.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_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
activity_main_drawer
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_menu_camera"
android:title="#string/menu_home" />
<item
android:id="#+id/nav_gallery"
android:icon="#drawable/ic_menu_gallery"
android:title="#string/menu_gallery" />
<item
android:id="#+id/nav_slideshow"
android:icon="#drawable/ic_menu_slideshow"
android:title="#string/menu_slideshow" />
<item
android:id="#+id/nav_tools"
android:icon="#drawable/ic_menu_manage"
android:title="#string/menu_tools" />
</group>
<item android:title="Communicate">
<menu>
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_menu_share"
android:title="#string/menu_share" />
<item
android:id="#+id/nav_send"
android:icon="#drawable/ic_menu_send"
android:title="#string/menu_send" />
</menu>
</item>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
</menu>
content_main:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
app_bar_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<include layout="#layout/content_main" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Add in you activity. It works
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_home) {
}else if (id == R.id.nav_logout) {
logOut(HomePage.this, "Logout due to nav. logout");
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
This question already has answers here:
How to change text of a TextView in navigation drawer header?
(11 answers)
How to set text to view from drawer header layout in navigation drawer without inflating view
(1 answer)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm trying to edit the text to show the email of the user and add a logout function to a menu item. I used the default Navigation drawer:
But on trying these two I always get
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
MainActivity.class
public class Options extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private Toast backToast;
private long backPressedTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_options);
String email2 = LoggedIn.getEmail(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = 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 = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery,
R.id.nav_tools)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
/////////////////////////HERE WHERE I EDIT THE TEXTVIEW
TextView txt_email = (TextView) findViewById(R.id.novoemailshow);
txt_email.setText(email2);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.options, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
/////////////////////////////THE LOGOUT FUNCTION
public void logout(View v) {
LoggedIn.savePassword(null, this);
LoggedIn.saveEmail(null, this);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finishAffinity();
}
}
nav_header_options.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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/nav_header_desc"
android:paddingTop="#dimen/nav_header_vertical_spacing"
app:srcCompat="#mipmap/ic_launcher_round" />
<TextView
android:id="#+id/novoemailshow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
options.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_settings"
android:onClick="logout"
android:orderInCategory="100"
android:title="Logout"
app:showAsAction="never" />
</menu>
I don't get it if MainActivity.class is created to handle all of it, then its created UI views and fragments, where should I be updating? And why are they null?
I made an empty activity and then I changed it to a DrawerLayout and every time I open the Menu and click an item the drawer is closing and nothing happens like i'm just opening and closing it, can't doing anything else.
This is the layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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=".MainActivity"
android:id="#+id/navigation_home_drawer">
<com.google.android.material.navigation.NavigationView
android:id="#+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/mainmenu"
>
</com.google.android.material.navigation.NavigationView>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.drawerlayout.widget.DrawerLayout>
And this is the Java Code
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private MapView mMapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = findViewById(R.id.navigation_home_drawer);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView navigationView =findViewById(R.id.navigation);
navigationView.setNavigationItemSelectedListener(this);
mMapView = findViewById(R.id.map);
initGoogleMap(savedInstanceState);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id) {
case R.id.nav_home:{
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
finish();
break;
}
case R.id.nav_profile: {
Intent i = new Intent(this, ProfileActivity.class);
startActivity(i);
finish();
break;
}
case R.id.nav_settings: {
Intent i = new Intent(this, SettingsActivity.class);
startActivity(i);
finish();
break;
}
}
return true;
}
}
Here's the menu layout
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/nav_home"
android:title="Home"
android:icon="#drawable/ic_home_black_24dp">
</item>
<item
android:id="#+id/nav_profile"
android:title="My Profile"
android:icon="#drawable/ic_person_black_24dp">
</item>
<item
android:id="#+id/nav_settings"
android:title="Settings"
android:icon="#drawable/ic_settigs">
</item>
</menu>
I also have the code for Map in this file, but it's not important, when I select an item from that menu I just want to change the activity to that, but nothing happens, only close the navigation, can you please tell me if I forgot to add something or what should I change to make the navigation work? Thank you in advance!
You can use this code to make navigation drawer :
NavigationView navigationView;
DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
navigationView = findviewbyid(R.id.nav_drawer_home);
drawerLayout = findviewbyid(R.id.drawer_home);
drawerLayout.requestLayout();
setUpNavigationView();
}
private void setUpNavigationView() {
navigationView.setNavigationItemSelectedListener(menuItem -> {
switch (menuItem.getItemId()) {
case R.id.nav_recharge:
break;
case R.id.nav_offers:
break;
case R.id.nav_rides:
break;
case R.id.nav_refer_friend:
break;
case R.id.nav_wallet:
break;
case R.id.nav_about_us:
break;
case R.id.nav_feedback:
break;
default:
break;
}
if (menuItem.isChecked())
menuItem.setChecked(false);
else
menuItem.setChecked(true);
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawers();
return;
}
super.onBackPressed();
}
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_recharge"
android:icon="#drawable/ic_recharge_wallet"
android:title="Rechange Wallet" />
<item
android:id="#+id/nav_offers"
android:icon="#drawable/ic_offers"
android:title="Offer's" />
<item
android:id="#+id/nav_rides"
android:icon="#drawable/ic_ride"
android:title="Rides" />
<item
android:id="#+id/nav_refer_friend"
android:icon="#drawable/ic_refer_friend"
android:title="Refer a friend" />
<item
android:id="#+id/nav_wallet"
android:icon="#drawable/ic_wallet_transfer"
android:title="Wallet Transfer" />
<item
android:id="#+id/nav_about_us"
android:icon="#drawable/ic_about_us"
android:title="About Us" />
<item
android:id="#+id/nav_feedback"
android:icon="#drawable/ic_feedback"
android:title="Feedback" />
</group>
<androidx.drawerlayout.widget.DrawerLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/home_content"/>
<com.google.android.material.navigation.NavigationView
android:clickable="true"
android:id="#+id/nav_drawer_home"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_home"
app:menu="#menu/nav_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
I am trying to use NavigationView from Android Support Design library in my app. For some reason, OnNavigationItemSelected listener is not being called. Here is my code
Activity Layout
<?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"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer_menu" />
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.DrawerLayout>
Activity onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutID());
toolbar = (Toolbar) findViewById(R.id.activity_toolbar);
setSupportActionBar(toolbar);
toolbar.inflateMenu(R.menu.common_menu);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
actionBar.setDisplayHomeAsUpEnabled(true);
}
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(final MenuItem menuItem) {
Snackbar.make(contentLayout, menuItem.getTitle() + " pressed", Snackbar.LENGTH_LONG).show();
menuItem.setChecked(true);
// allow some time after closing the drawer before performing real navigation
// so the user can see what is happening
drawerLayout.closeDrawer(GravityCompat.START);
mDrawerActionHandler.postDelayed(new Runnable() {
#Override
public void run() {
navigate(menuItem.getItemId());
}
}, DRAWER_CLOSE_DELAY_MS);
drawerLayout.closeDrawers();
return true;
}
});
usernameTextView = (TextView) findViewById(R.id.drawer_header_username);
usernameTextView.setText(getAppDContext().getAccount().getUsername());
}
When you make XML layout, you should write down NavigationView after BaseLayout (FrameLayout, LinearLayout, etc..)
<DrawerLayout>
<FrameLayout />
<NavigationView />
</DrawerLayout>
For me this did the trick!
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.bringToFront();
Your activity main layout should look like this:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/navigationDrawer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="#layout/activity_main_content" />
<android.support.design.widget.NavigationView
android:id="#+id/navigationView"
style="#style/NavigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
app:headerLayout="#layout/header"
app:menu="#menu/menu_drawer"/>
</android.support.v4.widget.DrawerLayout>
In this NavigationView I linked header.xml and menu_drawer.xml (from menu folder)
for example menu_drawer.xml :
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav1"
android:checked="true"
android:icon="#drawable/logo"
android:title="Navigation item 1"/>
<item
android:id="#+id/nav2"
android:icon="#drawable/logo"
android:title="Navigation item 2"/>
</group>
</menu>
than your java code:
public class ActivityMain extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpToolbar();
setUpNavDrawer();
}
private void setUpNavDrawer() {
NavigationView view = (NavigationView) findViewById(R.id.navigationView);
mDrawerLayout = (DrawerLayout) findViewById(R.id.navigationDrawer);
view.setNavigationItemSelectedListener(this);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawerOpen, R.string.drawerClose);
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
Check if this work for you. In my project works like a charm.