BottomNavigationView not showing in my activity - android

I am implementing BottomNavigationView using this link
i implemented everything step by step but my navigationview not showup at bottom of the screen.
this is what i done.
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
Intent intent = null;
BottomNavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navigationView = (BottomNavigationView) findViewById(R.id.navigation);
navigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if(id == R.id.program){
intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
if(id == R.id.access){
try {
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
overridePendingTransition(R.anim.push_up_in,
R.anim.push_up_out);
} else {
intent = new Intent(MainActivity.this, Access.class);
startActivity(intent);
finish();
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
if(id == R.id.informations){
intent = new Intent(MainActivity.this, Information.class);
startActivity(intent);
finish();
return true;
}
if(id == R.id.contact){
intent = new Intent(MainActivity.this, Contact.class);
startActivity(intent);
finish();
return true;
}
return false;
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu = navigationView.getMenu(); <---- // -->
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
and my activity.xml
<android.support.design.widget.CoordinatorLayout 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="match_parent"
android:background="#color/colorWhite">
<android.support.design.widget.BottomNavigationView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:design="http://schema.android.com/apk/res/android.support.design"
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_gravity="bottom"
design:menu="#menu/menu_main" />
</android.support.design.widget.CoordinatorLayout>
and i also updated gradle version to 25, otherwise it will not work.
compileSdkVersion 25
buildToolsVersion "24.0.3"
targetSdkVersion 25
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.android.support:design:25.0.0'

The reason it doesn't work is because menu is in the wrong namespace (design). Use the app namespace instead.
<android.support.design.widget.CoordinatorLayout
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="match_parent"
android:background="#color/colorWhite">
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_gravity="bottom"
app:menu="#menu/menu_main" />
</android.support.design.widget.CoordinatorLayout>

Try below xml. Don't forget to add app:layout_anchor and app:layout_anchorGravity="bottom". Here the BottomNavigationView is anchored to the FrameLayout with gravity bottom.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/rv"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Contents -->
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/nm_bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:foregroundTint="#color/colorAccent"
app:itemIconTint="#android:color/white"
app:itemTextColor="#android:color/white"
app:layout_anchor="#+id/rv"
app:layout_anchorGravity="bottom"
app:menu="#menu/nav_menu" />
</android.support.design.widget.CoordinatorLayout>

I had this problem because my BottomNavigationView was not showing in the design on the android studio. But when I ran the code it appeared on my phone.
So If you did not try running it. Run it and check before you search for answers maybe that is your problem

Find Styles.xml in Values.(res/Values/Styles.xml) Change this
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
to this:
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

Related

How to move to another activity using bottom navigation bar using kotlin in android studio? [duplicate]

//Here is my java code
public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
BottomNavigationView bottomNavigationView;
NavigationView navigationView;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull final MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
HomeFragment homeFragment=new HomeFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frameLayout,homeFragment).commit();
return true;
case R.id.navigation_stylist:
StylistFragment stylistsFragment=new StylistFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction1=getSupportFragmentManager().beginTransaction();
fragmentTransaction1.replace(R.id.frameLayout,stylistsFragment).commit();
return true;
case R.id.navigation_apps:
MyapptsFragment myaaptsFragment=new MyapptsFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction2=getSupportFragmentManager().beginTransaction();
fragmentTransaction2.replace(R.id.frameLayout,myaaptsFragment).commit();
return true;
case R.id.navigation_tips:
HairtipsFragment hairtipsFragment=new HairtipsFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction3=getSupportFragmentManager().beginTransaction();
fragmentTransaction3.replace(R.id.frameLayout,hairtipsFragment).commit();
return true;
case R.id.navigation_account:
AccountFragment accountFragment=new AccountFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction4=getSupportFragmentManager().beginTransaction();
fragmentTransaction4.replace(R.id.frameLayout,accountFragment).commit();
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//start onboarding when app is opening first time
isUserFirstTime = Boolean.valueOf(Utils.readSharedSetting(HomeActivity.this, PREF_USER_FIRST_TIME, "true"));
Intent introIntent = new Intent(HomeActivity.this, OnboardingActivity.class);
introIntent.putExtra(PREF_USER_FIRST_TIME, isUserFirstTime);
if (isUserFirstTime)
startActivity(introIntent);
setContentView(R.layout.activity_home);
bottomNavigationView = findViewById(R.id.bottom_navigation);
navigationView=findViewById(R.id.nav_drawer);
//bottom navigationview listener
bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
//navigation drawer listener
navigationView.setNavigationItemSelectedListener(this);
//open home fragment on first launch
HomeFragment homeFragment=new HomeFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frameLayout,homeFragment).commit();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
HomeFragment homeFragment=new HomeFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frameLayout,homeFragment).commit();
return true;
case R.id.nav_products:
StylistFragment stylistsFragment=new StylistFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction1=getSupportFragmentManager().beginTransaction();
fragmentTransaction1.replace(R.id.frameLayout,stylistsFragment).commit();
return true;
case R.id.nav_promotions:
MyapptsFragment myaaptsFragment=new MyapptsFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction2=getSupportFragmentManager().beginTransaction();
fragmentTransaction2.replace(R.id.frameLayout,myaaptsFragment).commit();
return true;
case R.id.nav_purchases:
HairtipsFragment hairtipsFragment=new HairtipsFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction3=getSupportFragmentManager().beginTransaction();
fragmentTransaction3.replace(R.id.frameLayout,hairtipsFragment).commit();
return true;
case R.id.nav_settings:
AccountFragment accountFragment=new AccountFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction4=getSupportFragmentManager().beginTransaction();
fragmentTransaction4.replace(R.id.frameLayout,accountFragment).commit();
return true;
}
return false;
}
}
// Here is my 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">
<android.support.design.widget.NavigationView
android:id="#+id/nav_drawer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:theme="#style/menu_text_style"
app:menu="#menu/navigation_drawer" />
<!--app:headerLayout="#layout/nav_header_main"-->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/shadow"
android:animateLayoutChanges="true">
</FrameLayout>
<View
android:id="#+id/shadow"
android:layout_width="match_parent"
android:layout_height="#dimen/_1sdp"
android:layout_above="#id/bottom_navigation"
android:background="#color/shadow"/>
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:itemIconTint="#color/navigationitem"
app:itemTextColor="#color/navigationitem"
app:menu="#menu/navigation_item"/>
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
I want to create both navigation drawer and bottom navigation in the same activity. I created XML design now I have to write java code for both. Bottom navigation is working perfectly but navigation item clicklistener is not working. I created fragments for navigation drawer and also for bottom navigation. When I click the items in navigation drawer it's not redirecting to respective fragment. The given clicklistener for navigation drawer is not at all working.
Solution:
Try the following steps to get it working:
Step1: Implement onNavigationItemSelected as shown below:
.... extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
Step2: Use the method generated by the interface as:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.your_drawer_item_id:
....
....
case R.id.your_drawer_item_id:
....
....
}
}
Step3: In your class declare a Global variable:
public NavigationView navigationView;
Step4: In your onCreate() initialize the variable as:
navigationView = (NavigationView) findViewById(R.id.your_nav_view);
Finally: Setup the navigationView:
navigationView.setNavigationItemSelectedListener(this);
That's it.
Hope it works.
DrawerLayout 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">
<include
layout="#layout/app_bar_vendor_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_drawer_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/White"
android:fitsSystemWindows="true"
app:itemBackground="#android:color/white"
app:itemIconTint="#color/bottom_color"
app:itemTextColor="#color/bottom_color"
app:headerLayout="#layout/nav_header_vendor_drawer_layout"
app:menu="#menu/vendor_drawer_menu" >
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
app_bar_vendor_drawer_layout xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="logixtic.android.web.vd.driver.activities.DriverDrawerActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/MyMaterialTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/Project_Standard"
app:popupTheme="#style/MyMaterialTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
android:layout_above="#+id/bottom_navigation">
</FrameLayout>
<View
android:layout_width="match_parent"
android:layout_height="3dp"
android:background="#drawable/toolbar_dropshadow_above"
android:layout_above="#id/bottom_navigation"/>
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:itemBackground="#color/White"
app:itemIconTint="#color/bottom_color"
app:itemTextColor="#color/bottom_color"
app:menu="#menu/vendor_bottom_navigation"/>
</RelativeLayout>
Try it.
You can use on the same activity using a method that recive a MenuItem parameter like this:
private void myClickItem(MenuItem item){
switch (item.getItemId()) {
case R.id.bottom_home:
// DO SOMETHING
break;
case R.id.drawer_main:
// DO SOMETHING
break;
}
}
Then, call like this:
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(item -> { // using lamda
myClickItem(item); //call here
return true;
});
NavigationView navigationView = findViewById(R.id.nv);
navigationView.setNavigationItemSelectedListener(item -> {
myClickItem(item); // call the same method here
drawerLayout.closeDrawers(); // bonus: hide navigation after click
return false;
});
You don't need to modify your xml res, it'll work fine.

Navigation drawer: How do I set the navigation item selected listener with custom tool bar?

I don't see any error when I open the navigation drawer, but it keeps getting closed whenever I select an item. Edit: My drawer gets closed automatically on item selection without showing the Toast message as mentioned in NavigationItemSelectedListener. The toast message is not displayed.
I have used a custom toolbar in which I have added an image view as a side menu button.
<?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=".CustomToolbar"
android:id="#+id/drawer_layout">
<com.google.android.material.navigation.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:headerLayout="#layout/header_file"
app:menu="#menu/main_manu"
android:layout_gravity="start"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bggradient">
<include
android:id="#+id/toolbar"
layout="#layout/layout_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</androidx.drawerlayout.widget.DrawerLayout>
public class CustomToolbar extends AppCompatActivity {
private Toolbar toolbar;
private DrawerLayout drawer;
private NavigationView navigationView;
private ActionBarDrawerToggle toggle;
private ImageView side_menu;
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (toggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_toolbar);
toolbar = (Toolbar) findViewById(R.id.navigation_bar);
side_menu = findViewById(R.id.side_menu);
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.navigation_view);
setSupportActionBar(toolbar);
toggle = new ActionBarDrawerToggle(this, drawer, R.string.open, R.string.close);
drawer.addDrawerListener(toggle);
toggle.syncState();
side_menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawer.openDrawer(Gravity.LEFT);
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home_menu: {
Toast.makeText(CustomToolbar.this, "Home Selected", Toast.LENGTH_SHORT).show();
}
case R.id.community_menu: {
Toast.makeText(CustomToolbar.this, "Community Selected", Toast.LENGTH_SHORT).show();
}
case R.id.posts_menu: {
Toast.makeText(CustomToolbar.this, "Posts Selected", Toast.LENGTH_SHORT).show();
}
case R.id.website_menu: {
Toast.makeText(CustomToolbar.this, "Website Selected", Toast.LENGTH_SHORT).show();
}
case R.id.share_menu: {
Toast.makeText(CustomToolbar.this, "Share Selected", Toast.LENGTH_SHORT).show();
}
case R.id.feedback_menu: {
Toast.makeText(CustomToolbar.this, "Feedback Selected", Toast.LENGTH_SHORT).show();
}
case R.id.about_menu: {
Toast.makeText(CustomToolbar.this, "About us Selected", Toast.LENGTH_SHORT).show();
}
case R.id.logout_menu: {
Toast.makeText(CustomToolbar.this, "Logout Selected", Toast.LENGTH_SHORT).show();
}
}
return false;
}
});
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
I have tried other method with default toolbar, and it was working properly but I am not able to figur out the problem with custom toolbar. I wanted to display a toast on item selection inside the navigation drawer. Please help me find the solution...
Thank you.
In onNavigationItemSelected, Change this
return false;
to
return true;
After so long finally I found the solution to my problem. But I don't know why it was happening like that but I'm happy that it is finally working. And I am also very happy to share it with those who may experience the same issue in the future which I hope they won't.
I referred to the link from the Git hub for this solution. Link: https://github.com/priyalbhatewara123/Navigation-Drawer--Android
Finally here is the solution I found,
I just added the following lines of codes below </ScrollView> which was above <ScrollView> in the problematic code used in my activity_custom_toolbar.xml.
<com.google.android.material.navigation.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:headerLayout="#layout/header_file"
app:menu="#menu/main_manu"
android:layout_gravity="start"/>
I'm also adding the code after changes,
<?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=".CustomToolbar"
android:id="#+id/drawer_layout">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bggradient">
<include
android:id="#+id/toolbar"
layout="#layout/layout_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
<com.google.android.material.navigation.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:headerLayout="#layout/header_file"
app:menu="#menu/main_manu"
android:layout_gravity="start"/>
</androidx.drawerlayout.widget.DrawerLayout>

Not recognize one menu item in Android

I don't understand why in this case is not recongnizing my menu item.
I have another activities with similar code and it's working fine, but in this case i'm having NPE.
Layouts
General (activity_completas)
<?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=".activities.CompletasActivity">
<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_breviario_general" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
content_breviario_general
<?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">
<include
android:id="#+id/include"
layout="#layout/tv_zoomable" />
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"
app:layout_constraintBottom_toTopOf="#+id/include"
app:layout_constraintEnd_toStartOf="#+id/include"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
Menu
<?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"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".activities.BreviarioActivity">
<item
android:id="#+id/item_voz"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:icon="#drawable/ic_play"
android:visible="false"
android:title="#string/leer"
app:showAsAction="ifRoom" />
<item
android:id="#+id/item_calendario"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:icon="#drawable/ic_calendar_toolbar"
android:title="#string/all_calendar"
app:showAsAction="ifRoom" />
</menu>
Java code
Relevant parts only for this case:
public class CompletasActivity extends AppCompatActivity {
//...
private Menu menu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_completas);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
showData();
}
private void showData() {
sbReader = new StringBuilder();
//I fill sbReader correctly
if (sbReader.length()>0) {
menu.findItem(R.id.item_voz).setVisible(true); //******NPE here*******
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
this.menu = menu;
getMenuInflater().inflate(R.menu.toolbar_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (tts != null) {
tts.cerrar();
}
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.item_voz:
String html = String.valueOf(Utils.fromHtml(sbReader.toString()));
String[] textParts = html.split(SEPARADOR);
tts = new TTS(getApplicationContext(), textParts);
return true;
case R.id.item_calendario:
Intent i = new Intent(this, CalendarioActivity.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
if (tts != null) {
tts.cerrar();
}
}
}
Error
java.lang.NullPointerException: Attempt to invoke interface method
'android.view.MenuItem android.view.Menu.findItem(int)' on a null
object reference
I do the same thing in another activities and i don't have NEP. What's happening here?
You are getting null point exception because your menu isn't instantiated. As i can see, your are calling showData before creating the menu. Call showData in the onCreateMenu. This should solve your problem.

Navigation item click event doesn’t work in Android

Navigationview click event doesn’t work in Android. I click to item-element but the codes doesn’t work. The Java and XML Codes are in below.
Codes:
menulayout = (DrawerLayout)findViewById(R.id.drawerlayout);
navview = (NavigationView)findViewById(R.id.navview);
navview.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener () {
public boolean onNavigationItemSelected(MenuItem secilen){
Toast.makeText(getApplicationContext(), "tıklandı" + secilen, Toast.LENGTH_LONG).show();
if(secilen.getItemId() == R.id.profilitem){
startActivity(new Intent(getApplicationContext(), profil.class));
}else if(secilen.getItemId() == R.id.haberitem){
startActivity(new Intent(getApplicationContext(), haber.class));
}else if(secilen.getItemId() == R.id.cashgonderitem){
startActivity(new Intent(getApplicationContext(), cashgonder.class));
}else if(secilen.getItemId() == R.id.cashalitem){
startActivity(new Intent(getApplicationContext(), cashal.class));
}else if(secilen.getItemId() == R.id.ayaritem){
startActivity(new Intent(getApplicationContext(), ayar.class));
}else if(secilen.getItemId() == R.id.yardimitem){
startActivity(new Intent(getApplicationContext(), yardim.class));
}
return false;
}
});
XML Code :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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"
android:id="#+id/drawerlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".navdraweroyun"
android:fitsSystemWindows="true"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<include
layout="#layout/activity_oyunbar"/>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/navmenu"
/>
</android.support.v4.widget.DrawerLayout>
I hope I haven't a error in XML.
How I can resolve this problem?
I hope you are understand. I doesn't have a good English.
I need your help.

Navigation Drawer click not triggering

enter image description hereAs you can see I have added 6 item in navigation drawer but on clicking Logout it is not triggered. And sorry for bad code format. I'm new here.
#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_log_out) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.nav_profile:
break;
case R.id.nav_wallet:
break;
case R.id.nav_search:
break;
case R.id.nav_about_us:
break;
case R.id.nav_contact_us:
break;
case R.id.nav_log_out:
Intent intent = new Intent(this,LogIn.class);
FirebaseAuth.getInstance().signOut();
startActivity(intent);
}
This is my XML file for menu item. The id are the same I declared in the XML file. Log out in action bar is working fine but it is not working in Navigation 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_profile"
android:icon="#drawable/ic_person_black_24dp"
android:title="Profile" />
<item
android:id="#+id/nav_wallet"
android:icon="#drawable/ic_attach_money_black_24dp"
android:title="EasyFare Wallet" />
<item
android:id="#+id/nav_search"
android:icon="#drawable/ic_directions_bus_black_24dp"
android:title="Search Bus" />
<item
android:id="#+id/nav_about_us"
android:icon="#drawable/ic_folder_shared_black_24dp"
android:title="About Us"/>
<item
android:id="#+id/nav_contact_us"
android:icon="#drawable/ic_email_black_24dp"
android:title="Contact Us" />
<item
android:id="#+id/nav_log_out"
android:icon="#drawable/ic_exit_to_app_black_24dp"
android:title="Log Out" />
</group>
</menu>
activity file with DrawerLayout
<?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">
<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_main_drawer" />
</android.support.v4.widget.DrawerLayout>
You have to add brackets for case in logout..
case R.id.nav_log_out:
{
Intent intent = new Intent(this,LogIn.class);
FirebaseAuth.getInstance().signOut();
startActivity(intent);
}
Could you include the code in your activity's onCreate?
One possibility is that you forgot to register your activity as the listener for the navigation view.
mNavigationView.setNavigationItemSelectedListener(this)
Clicking on some other item, let's say the second one, gets this item triggered?
If yes add a break statement in your logout case and also create a default case.
You could also try replacing your code with the following sample.
#SuppressWarnings("StatementWithEmptyBody")
#Override public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.nav_profile:
break;
case R.id.nav_wallet:
break;
case R.id.nav_search:
break;
case R.id.nav_about_us:
break;
case R.id.nav_contact_us:
break;
case R.id.nav_log_out:
{
Intent intent = new Intent(this,LogIn.class);
FirebaseAuth.getInstance().signOut();
startActivity(intent);
break;
}
DrawerLayout drawer;
drawer = findViewById(R.id.THE_ID_OF_YOUR_DRAWER);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Also make sure that in your OnCreate , OnStart or onResume you include the following
DrawerLayout drawer;
drawer = findViewById(R.id.THE_ID_OF_YOUR_DRAWER);
I will provide you with a code i use for a project of mine and try to see if you find any differences that would explain the fact your code does not work.
AnnouncementsActivity.java
.
.
.
.
public class AnnouncementsActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_announcements);
.
.
.
.
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer;
drawer = findViewById(R.id.drawer_layout_astiko);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
toolbar.setNavigationIcon(R.mipmap.ic_toolbar);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
.
.
.
.
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_first_item) {
if(prev_activity_routes){
Intent intent = new Intent(this,RoutesActivity.class);
intent.putExtra("Direction Forth",bus_direction_forth);
intent.putExtra("Team",team);
intent.putExtra("Route name", value1);
intent.putExtra("odigos_onomateponimo",odigos_onomateponimo);
startActivity(intent);
}else{
if(isAstiko){
Intent intent = new Intent(this,TicketIssuanceActivityAstiko.class);
intent.putExtra("Direction Forth",bus_direction_forth);
intent.putExtra("Team",team);
intent.putExtra("Route name", value1);
intent.putExtra("odigos_onomateponimo",odigos_onomateponimo);
startActivity(intent);
}else{
Intent intent = new Intent(this,TicketIssuanceActivity.class);
intent.putExtra("Direction Forth",bus_direction_forth);
intent.putExtra("Team",team);
intent.putExtra("Route name", value1);
intent.putExtra("odigos_onomateponimo",odigos_onomateponimo);
startActivity(intent);
}
}
} else if (id == R.id.nav_second_item) {
Intent intent = new Intent(this,DefinedTicketsActivity.class);
intent.putExtra("Direction Forth",bus_direction_forth);
intent.putExtra("Team",team);
intent.putExtra("Route name", value1);
intent.putExtra("odigos_onomateponimo",odigos_onomateponimo);
intent.putExtra("PreviousActivityRoutes",prev_activity_routes);
intent.putExtra("isAstiko",isAstiko);
startActivity(intent);
}
.
.
.
.
}else if (id == R.id.nav_eighth_item) {
Intent intent = new Intent(this, SignInActivity.class);
startActivity(intent);
}
DrawerLayout drawer;
drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
}
ActivityAnnouncements.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">
<include
layout="#layout/app_bar_announcements"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="500dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:theme="#style/NavigationDrawerStyle"
app:headerLayout="#layout/my_nav_header"
app:menu="#menu/my_drawer" />
</android.support.v4.widget.DrawerLayout>
app_bar_announcements.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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="com.e_analysis.AlphaPro.MobileTicketing.AnnouncementsActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/MyTheme">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="65dp"
android:background="?attr/colorPrimary"
app:popupTheme="#style/MyTheme"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_announcements" />
</android.support.design.widget.CoordinatorLayout>
content_announcements.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="-0dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:orientation="vertical"
android:background="#color/colorPrimary"
android:gravity="fill"
tools:context="com.e_analysis.AlphaPro.MobileTicketing.AnnouncementsActivity"
tools:showIn="#layout/app_bar_announcements">
.
.
.
.
</LinearLayout>
my_drawer.xml in the menu subfolder
<?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">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_first_item"
android:icon="#mipmap/ic_printer_black"
android:title="#string/nav_first_item_value"/>
<item
android:id="#+id/nav_second_item"
android:icon="#mipmap/ic_tune_vertical"
android:title="#string/nav_second_item_value" />
.
.
.
.
<item
android:id="#+id/nav_eighth_item"
android:icon="#mipmap/ic_logout"
android:title="#string/nav_eighth_item_value" />
</group>
</menu>
my_nav_header.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_vertical_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
.
.
.
.
</LinearLayout>
This code is working (not as it is ofcourse) so try to do some cross-checking with it and see what you are missing. Most probably it will be something easy to overlook and frustrating when you find out. Good luck!

Categories

Resources