Android Studio Swictch-case Instance not working properly - java

I have been making an app which has a navigation drawer, but that navigation drawer isn't working with the switch case I've made. The id's are right.
For starters here's the shortened version of my code:
Here's my java class:
public class Image extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
//DRAWER LAYOUT
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView mNavigationView = (NavigationView) findViewById(R.id.nav_menu);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener(){
#Override public boolean onNavigationItemSelected(MenuItem menuItem)
{ switch (menuItem.getItemId())
{
case(R.id.nav_account): Intent accountActivity = new Intent(getApplicationContext(), Welcome.class);
startActivity(accountActivity);
case(R.id.nav_exercises): Intent accountActivity1 = new Intent(getApplicationContext(), Video.class);
startActivity(accountActivity1);
case(R.id.nav_tips): Intent accountActivity2 = new Intent(getApplicationContext(), Image.class);
startActivity(accountActivity2);
}
return true;
} );
//Navigation Drawer
}
//FOR NAVIGATION DRAWER
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
//Navigation Drawer End
}
Here are the XML's:
navigation_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/nav_account"
android:icon="#mipmap/ic_person_outline_black_24dp"
android:title="My Account" />
<item android:id="#+id/nav_settings"
android:icon="#mipmap/ic_settings_black_24dp"
android:title="Settings"/>
<item android:id="#+id/nav_exercises"
android:icon="#mipmap/ic_accessibility_black_24dp"
android:title="Exercises"/>
<item android:id="#+id/nav_tips"
android:icon="#mipmap/ic_face_black_24dp"
android:title="Tips"/>
<item android:id="#+id/nav_scheduler"
android:icon="#mipmap/ic_date_range_black_24dp"
android:title="My Schedule"/>
<item android:id="#+id/nav_info"
android:icon="#mipmap/ic_info_outline_black_24dp"
android:title="Info"/>
<item android:id="#+id/nav_logout"
android:icon="#mipmap/ic_input_black_24dp"
android:title="Logout"/>
</menu>
Here's where I apply the drawer:
<?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.Welcome.Video"
android:id="#+id/drawerLayout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<VideoView
android:id="#+id/videoView"
android:layout_width="wrap_content"
android:layout_height="259dp" />
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="videoplay"
android:text="Play" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/navigation_menu"
app:headerLayout="#layout/navigation_header"
android:layout_gravity="start"
android:id="#+id/nav_menu"
>
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
What happens is when the navigation drawer, I click nav_exercises case but what shows is the view of the supposed to be for the nav_tips. I click back and then it goes to the exercises part. The TIPS is working just as it is.
But the EXERCISES part, it shows the TIPS view and then when you press "back" it goes to the right place. In other words it's somehow overlapping with the other view.
What did I do wrong? I'm sure the class and ID's are in the right places, I've checked for an hour really.
Any help is appreciated. Thank you very much!

you need to add break; otherwise every case will be executed
switch (menuItem.getItemId())
{
case(R.id.nav_account): Intent accountActivity = new Intent(getApplicationContext(), Welcome.class);
startActivity(accountActivity);
break;
//^^^
case(R.id.nav_exercises): Intent accountActivity1 = new Intent(getApplicationContext(), Video.class);
startActivity(accountActivity1);
break;
//^^^
case(R.id.nav_tips): Intent accountActivity2 = new Intent(getApplicationContext(), Image.class);
startActivity(accountActivity2);
break;// not needed at last but good practice
}

You need to break the switch case
like
switch (request.getMethod()) {
case Method.GET:
...
break;
case Method.DELETE:
...
break;
case Method.POST:
...
break;
case Method.PUT:
...
break;
default:
throw new IllegalStateException("Unknown method type.");
}

Related

Navigation Drawer is not handling click events

Problem 1- My navigation drawer is not handling click events.
Problem 2- Instead of showing hamburger icon it is showing backward arrow.
I tried searching already but couldn't find answer. I also tried adding .bringToFront() method but still not working.
MainActivity.java:-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextView navUserName = findViewById(R.id.textViewNav_username);
TextView navUserEmail = findViewById(R.id.textViewNav_useremail);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference volunteerRef = dbRef.child("Volunteer").child(currentUser.getUid());
//If current user is null go to login activity
if (currentUser == null) {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
//Creates hamburger animated icon
drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle actionBarDrawerToggle= new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open,R.string.navigation_drawer_close);
drawer.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
//Sets click listner to navigation item 1/2
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.bringToFront();
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_option_home);
// 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_option_profile, R.id.nav_option_contact, R.id.nav_option_about, R.id.nav_option_share,R.id.nav_option_logout)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
//Sets click listner to navigation item 2/2
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Log.d("main1122", "inside listner");
switch (item.getItemId()){
case R.id.nav_option_home:
Log.d("main1122", "Clicked item" + item.getItemId());
getSupportFragmentManager().beginTransaction().replace(R.id.content_nav_drawer,
new HomeFragment()).commit();
break;
case R.id.nav_option_profile:
Log.d("main1122", "Clicked item" + item.getItemId());
getSupportFragmentManager().beginTransaction().replace(R.id.content_nav_drawer,
new profile()).commit();
break;
case R.id.nav_option_contact:
getSupportFragmentManager().beginTransaction().replace(R.id.content_nav_drawer,
new contact()).commit();
break;
case R.id.nav_option_about:
getSupportFragmentManager().beginTransaction().replace(R.id.content_nav_drawer,
new AboutFragment()).commit();
break;
case R.id.nav_option_share:
//TODO: Share app action
Toast.makeText(this,"Share clicked",Toast.LENGTH_SHORT).show();
break;
case R.id.nav_option_logout:
//TODO: Logout action
break;
}
drawer.closeDrawer(GravityCompat.START);
//Return false will make menu item unselected(not highlighted)
return true;
}
activity_main.xml (Contains R.id.nav_view) :-
<?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_nav__drawer"
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_nav__drawer"
app:menu="#menu/activity_nav__drawer_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
mobile_navigation.xml (Contains fragments which I want to launch after clicking menu items) :-
<?xml version="1.0" encoding="utf-8"?>
<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.helpinghandsorg.helpinghands.ui.home.HomeFragment"
android:label="#string/menu_home"
tools:layout="#layout/fragment_home"/>
<fragment
android:id="#+id/nav_about"
android:name="com.helpinghandsorg.helpinghands.AboutFragment"
android:label="#string/menu_about"
tools:layout="#layout/fragment_about">
<action
android:id="#+id/action_nav_about_to_nav_home"
app:destination="#id/nav_home" />
</fragment>
<fragment
android:id="#+id/nav_contact"
android:name="com.helpinghandsorg.helpinghands.ui.contact.contact"
android:label="#string/menu_contact"
tools:layout="#layout/contact_fragment">
<action
android:id="#+id/action_nav_contact_to_nav_home"
app:destination="#id/nav_home" />
</fragment>
<fragment
android:id="#+id/nav_profile"
android:name="com.helpinghandsorg.helpinghands.ui.profile.profile"
android:label="#string/menu_profile"
tools:layout="#layout/profile_fragment">
<action
android:id="#+id/action_nav_profile_to_nav_home"
app:destination="#id/nav_home" />
</fragment>
</navigation>
activity_nav_drawer_drawer.xml (Contains Menu Item IDs):-
<?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="navi_view">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_option_home"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/menu_home" />
<item
android:id="#+id/nav_option_profile"
android:icon="#drawable/ic_account_circle_black_24dp"
android:title="#string/menu_profile" />
<item
android:id="#+id/nav_option_contact"
android:icon="#drawable/ic_email_black_24dp"
android:title="#string/menu_contact" />
<item
android:id="#+id/nav_option_about"
android:icon="#drawable/ic_info_black_24dp"
android:title="#string/menu_about" />
<item
android:id="#+id/nav_option_share"
android:icon="#drawable/ic_menu_share"
android:title="#string/menu_share" />
<item
android:id="#+id/nav_option_logout"
android:icon="#drawable/ic_exit_to_app_black_24dp"
android:title="#string/menu_logout" />
</group>
</menu>
Answer for my 2nd question.
PROBLEM- Instead of showing hamburger icon it is showing backward arrow.
Solution- Actually it was because I didn't provide ID of home fragment on my AppbarConfiguration.Builder
Before-
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_option_profile, R.id.nav_option_contact, R.id.nav_option_about, R.id.nav_option_share,R.id.nav_option_logout)
.setDrawerLayout(drawer)
.build();
After-
mAppBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_home,
R.id.nav_option_profile, R.id.nav_option_contact, R.id.nav_option_about, R.id.nav_option_share,R.id.nav_option_logout)
.setDrawerLayout(drawer)
.build();

Navigation Drawer App does not change fragments when clicked

Good Morning, I am a newbie programmer, and I use Navigation Drawer Android Studio Activity to start. Everything is ok when I compile, but when I use the app and click on the different options, nothing happens (I mean that the layout doesn't change and remain on the activity_main.xml). I look for other questions but (I think) no one has had my problem.
MainActivity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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, "Ma giusto a provare", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
switch(item.getItemId()) {
case R.id.nav_home:
ft.replace(R.id.fragment_container
, new CulturaClass()).commit();
break;
case R.id.nav_gallery:
ft.replace(R.id.fragment_container
, new CulturaClass()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
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
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
</android.support.constraint.ConstraintLayout>
activity_main_drawer.xml
<?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_Cultura" />
<item
android:id="#+id/nav_slideshow"
android:icon="#drawable/ic_menu_slideshow"
android:title="#string/menu_organizer" />
<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>
</menu>
fragment_cultura.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cultura generale!"
tools:layout_editor_absoluteX="171dp"
tools:layout_editor_absoluteY="320dp" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="VVVVai!"
tools:layout_editor_absoluteX="161dp"
tools:layout_editor_absoluteY="403dp" />
</android.support.constraint.ConstraintLayout>
CulturaClass.java
public class CulturaClass extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_cultura,container,false);
}
activity_main.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_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" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="hello" />
</android.support.v4.widget.DrawerLayout>
Instead of R.id.fragment_container provide name for FrameLayout in activity_main.xml and pass that name while replacing fragment i.e.
case R.id.nav_home:
ft.replace(R.id.<name_of_framelayout>, new CulturaClass()).commit();
break;
case R.id.nav_gallery:
ft.replace(R.id.<name_of_framelayout>, new CulturaClass()).commit();
break;
This might work for you
Because you are replacing fragment with same class:
case R.id.nav_home:
ft.replace(R.id.fragment_container
, new CulturaClass()).commit(); //Same Class
break;
case R.id.nav_gallery:
ft.replace(R.id.fragment_container
, new CulturaClass()).commit(); //Same Class
break;
You can do this thing simple and easy way using common function or method and You never do mistake.
You have two option to use this One is using JAVA and second, is KOTLIN
The first Method I write below check this:
If you are using java, use like this method
First, create one function i.e name setFragment and pass the parameter Fragment class and second is a title (a Title is an optional if you use or not)
Declare the globally variable
private Fragment fragment = null;
//create function for replace fragment
private void setFragment(Fragment fragmentName, String title) {
fragment = fragmentName;
if (fragment != null) {
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.framelayout, fragment, fragment.getTag()).commit();
}
setTitle("Dashboard");
// Close the navigation drawer
drawerLayout.closeDrawers();
}
If you are using KOTLIN:
First, create one function i.e name openFragment and pass the parameter Fragment class and second is a title (a Title is an optional if you use or not)
Declare the globally variable
private var fragment: Fragment? = null
//create function for replace fragment
fun openFragment(fragmentClass: Fragment, titleName: String) {
//pass the current fragment class name which you replace
fragment = fragmentClass
//check first fragment is null or not
if (fragment != null) {
val fragmentManager = supportFragmentManager
fragmentManager.beginTransaction()
.replace(R.id.framelayout, fragment!!, fragment!!.tag).commit()
}
title = titleName // replace the titlename
//check the drawerLayout close or not
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START)
}
}

OnOptionsItemSelected doesn't work on android API 19 (but works on android 24)

I have the following code in my activity class
public class admin_fab_features_grid extends
base_activity_for_admin_home_page implements Parcelable {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity_context = getApplicationContext();
Intent iIntent= getIntent();
Bundle b = iIntent.getExtras();
// display the admin_fab_features_grid that contain the dashboard list of all the admin options
setContentView(R.layout.admin_fab_features_grid);
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar_toolbar);
setSupportActionBar(toolbar);
}
The base_activity_for_admin_home_page.java has the following code
public class base_activity_for_admin_home_page extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(Tag, " Into base activity for parent menu");
_context = getApplicationContext();
// display the admin_fab_features_grid that contain the dashboard list of all the admin options
setContentView(R.layout.admin_fab_features_grid);
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar_toolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_admin_home_page, menu);
Log.d(Tag, "inflate done");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.actionbar_settings:
return true;
}
}
}
The menu_admin_home_page has the following 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"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MyActivity">
<item android:id="#+id/actionbar_settings"
android:title="#string/actionbar_settings"
android:orderInCategory="100"
app:showAsAction="never" />
<!--
<item android:id="#+id/actionbar_dropoff"
android:title="#string/actionbar_dropoff"
android:orderInCategory="90"
app:showAsAction="never" />
<item android:id="#+id/actionbar_signin"
android:title="#string/actionbar_signin"
android:orderInCategory="85"
app:showAsAction="never" />
-->
<item android:id="#+id/actionbar_logout"
android:title="#string/actionbar_logout"
android:orderInCategory="80"
app:showAsAction="never" />
</menu>
The "Settings" menu is enabled in the Toolbar. I can see ":" in the Toolbar. On a device that has Android API24 I am able to click on it and the OnOptionsItemSelected function is getting called. But the same application on a device that has Android API 19 the OnOptionsItemSelected does not get called. Can someone help?
change onOptionsItemSelected() to this and try
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.actionbar_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
Since you set the showAsAction attribute to never, then these menu items will never show as action views. Try this:
showAsAction = ifRoom|withText
switch (item.getItemId()) {
case R.id.actionbar_settings:
doyouraction();
return true;
default: return super.onOptionsItemSelected(item);
} }
Solved it after 4 days of pain.
What occurred is that the CoordinatorLayout overlays the GridView on top of the toolbar and that is why the onOptionsItemSelected icons were not getting called. They're being blocked. Toolbar doesn't overlay on-top of the GridView like an actionbar. Its a view itself. To solve this I removed the CoordinatorLayout add an id to the Toolbar and then add android:layout_below="#id/toolbar".
<?xml version="1.0" encoding="utf-8"?>
<!--
// <android.support.design.widget.CoordinatorLayout
-->
<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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="fab_features.admin_fab_features_grid">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#id/app_bar_toolbar"
style="#style/Widget_v7_Toolbar_style"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.Toolbar
android:id="#id/app_bar_toolbar"
style="#style/Widget_v7_Toolbar_style"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#id/admin_fab_features_grid"
style="#style/admin_fab_features_grid_gridview"
android:layout_below="#id/app_bar_toolbar"
/>
</LinearLayout>

Android Navigation Menu on item selected listener not firing

I have a navigation menu set up but whenever I select an item from it the onNavigationItemSelected does not get called.
MapsActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
initializeMap();
googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
navigationMenu = (NavigationView) findViewById(R.id.navigation_menu);
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);
toast = Toast.makeText(this, "test", Toast.LENGTH_LONG);
navigationMenu.setNavigationItemSelectedListener(this);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
toast.show();
Log.v("NAV", "Navigation item selected");
Log.v("ITEM", item.getItemId() + "");
switch (item.getItemId()){
case R.id.nav_restaurant: {
//do stuff
}
case R.id.nav_pharmacy: {
//do stuff
}
case R.id.nav_bank: {
//do stuff
}
}
return false;
}
activity_maps.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout">
<android.support.design.widget.NavigationView
android:layout_width="200dp"
android:layout_height="match_parent"
app:menu="#menu/navigation_menu"
android:id="#+id/navigation_menu"
android:layout_gravity="start"
app:headerLayout="#layout/navigation_header">
</android.support.design.widget.NavigationView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Main Layout"
android:layout_gravity="center"
android:textAlignment="center"
android:textSize="30dp"/>
</LinearLayout>
<fragment
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.damia.placefinder.activities.MapsActivity" />
The navigation menu opens and closes perfectly fine, and even closes once I select an item, but neither the two logs or the toast appears, showing that the onNavigationItemSelected was never called.
I suspect it has something to do with everything (the maps and nagivation drawer) being in the same activity but I'm not sure.
Because your NavigationView was covered by your LinearLayout and fragment. Please put the sequence of your views in activity_maps.xml in this way:
<DrawerLayout >
<LinearLayout />
<fragment />
<NavigationView /> <!-- on the top of views -->
</DrawerLayout>
And DO NOT FORGET return true; in your listener.

How to add back button arrow functionality in navigation bar

I am beginner programmer and just resent started android developing.
Watched many answers and couldn't find answer witch would fit for me.
I have added back arrow button in my action bar, but couldn't figure out how to add navigation to first loaded screen.
MainActivity.java
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);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final 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);
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
toggle.setDrawerIndicatorEnabled(getSupportFragmentManager().getBackStackEntryCount() == 0);
}
});
}
#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;
}
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
TextView text = (TextView) findViewById(R.id.container_text);
Fragment fragment = null;
if (id == R.id.nav_about) {
fragment = DemoFragment.newInstance("about");
text.setText("1");
} else if (id == R.id.nav_settings) {
fragment = DemoFragment.newInstance("nav settings");
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(fragment.getClass().getSimpleName())
.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
DemoFragment.java
public class DemoFragment extends Fragment {
public static final String TEXT = "text";
public static DemoFragment newInstance(String text) {
Bundle args = new Bundle();
args.putString(TEXT, text);
DemoFragment fragment = new DemoFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_demo, container, false);
String text = getArguments().getString(TEXT);
return view;
}
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
activity_main.xml
<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" />
app_bar_main.xml
<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"
android:fitsSystemWindows="true"
tools:context="lt.simbal.drawer.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.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" />
</android.support.design.widget.AppBarLayout>
<include
android:id="#+id/container"
layout="#layout/content_main" />
<android.support.design.widget.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:src="#android:drawable/ic_dialog_email" />
content_main.xml
<FrameLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="lt.simbal.drawer.MainActivity"
tools:showIn="#layout/app_bar_main">
<TextView
android:id="#+id/container_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MAIN_ACTIVITY" />
fragment_demo.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent" />
nav_header_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
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_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#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:paddingTop="#dimen/nav_header_vertical_spacing"
android:src="#android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="#style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="android.studio#android.com" />
activity_main_drawer.xml
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_about"
android:icon="#drawable/ic_menu_camera"
android:title="#string/about" />
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_menu_manage"
android:title="#string/settings" />
</group>
You need to call setHomeAsUpIndicator & setDisplayHomeAsUpEnabled
Set an alternate drawable to display next to the icon/logo/title when
DISPLAY_HOME_AS_UP is enabled. This can be useful if you are using
this mode to display an alternate selection for up navigation, such as
a sliding drawer.
ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
{
......
actionBar.setDisplayHomeAsUpEnabled(true); //Set this to true if selecting "home" returns up by a single level in your UI rather than back to the top level or front page.
actionBar.setHomeAsUpIndicator(R.drawable.Your_Icon); // set a custom icon for the default home button
}
Now
For this handling need to override onOptionsItemSelected(MenuItem item) method in your Activity .
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.home:
// Add your LOGIC Here
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
Alright make sure u do declare activity layout as below -
<activity
android:name="com.example.myfirstapp.DisplayMessageActivity"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<!-- The meta-data element is needed for versions lower than 4.1 -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
Now in every activity add below code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
add below code in onCreate
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.back_dark);
}
R.drawable.back_dark is back button image
remove this actionBar.setHomeButtonEnabled(true); from your code
EDITED: found one thing, change below method
#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;
//}
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
otherwise your all code is perfect! no need to change naythig
#JonasSeputis: i have use your activity and run in android device its showing toast "Back button clicked" check below code and comment other code for sometime
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
/*DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final 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);
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
toggle.setDrawerIndicatorEnabled(getSupportFragmentManager().getBackStackEntryCount() == 0);
}
});*/
}
#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;
}*/
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(), "Back button clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
}
In your
#Override
public boolean onOptionsItemSelected(MenuItem item){
if (id == android.R.id.home){
// add intent to class you wish to navigate
Intent i = new Intent("com.your.package.classname");
startActivity(i);
}
}
just add this line in
onCreate:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Categories

Resources