Navigation Drawer is not handling click events - java

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

Related

Handle clicks on menu item in toolbar in android

How to handle clicks from a toolbar with Navigation Component in android?
I have a MaterialToolbar in an activity with a menu in xml, the menu shows up and accepts clicks but no action is executed.
This is how I initialize the navigation component:
binding = DataBindingUtil.setContentView(this, R.layout.activity_home);
navController = Navigation.findNavController(this, R.id.fragment_container);
appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph())
.setDrawerLayout(binding.activityHome)
.build();
NavigationUI.setupWithNavController(binding.navigationView, navController);
NavigationUI.setupWithNavController(binding.toolBar, navController, appBarConfiguration);
This is my Toolbar menu, it has only one item that will open a DialogFragment:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/dialog_account"
android:icon="#drawable/icon_account"
android:title="#string/dialog_account"
app:showAsAction="always" />
</menu>
Then this is the dialog in the navigation_graph
<dialog
android:id="#+id/dialog_account"
android:name="my.package.name.dialogs.DialogAccount"
android:label="#string/dialog_account"
tools:layout="#layout/dialog_account" />
This is the activity layout, nothing fancy there:
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<data></data>
<androidx.drawerlayout.widget.DrawerLayout
android:id="#+id/activity_home"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="end">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimaryDark"
app:layout_constraintBottom_toTopOf="#+id/fragment_container"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
<com.google.android.material.appbar.MaterialToolbar
android:id="#+id/tool_bar"
style="#style/toolbar_style"
app:menu="#menu/toolbar" />
</com.google.android.material.appbar.AppBarLayout>
<fragment
android:id="#+id/fragment_container"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="#dimen/null_dimen"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/app_bar"
app:navGraph="#navigation/nav_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/navigation_view"
style="#style/navigation_view" />
</androidx.drawerlayout.widget.DrawerLayout>
</layout>
The Activity layout has a NavigationView and a MaterialToolbar, the navigation from the NavigationView works fine, but I can't find a way to open my dialog from the Toolbar even though it seems like is taking clicks but doing nothing. I have tried with onCreateOptionsMenu but it does not get triggered, guess the Navigation Component is working but my dialog is not opening on touching of the menu.
What am I missing here, any hand?
To handle on click on Toolbar simply use "setOnMenuItemClickListener" by providing id of the toolbar.
mToolbar= findViewById(R.id.main_tollbar);
mToolbar.inflateMenu(R.menu.game_menu);
mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch(item.getItemId()){
case R.id.search_menu:
Toast.makeText(MainActivity.this,"Search Successful",Toast.LENGTH_LONG).show();
break;
case R.id.menus_logout:
Toast.makeText(MainActivity.this,"Logout Successful",Toast.LENGTH_LONG).show();
break;
case R.id.acc_settings:
Toast.makeText(MainActivity.this,"Setting Successful",Toast.LENGTH_LONG).show();
break;
case R.id.about_menu:
Toast.makeText(MainActivity.this,"About Successful",Toast.LENGTH_LONG).show();
break;
case R.id.feedback_menu:
Toast.makeText(MainActivity.this,"Feedback Successful",Toast.LENGTH_LONG).show();
break;
}
return true;
}
});
If you are using the Toolbar (without using setSupportActionBar(toolbar);) you have to use:
NavigationUI.setupWithNavController(toolbar,navController,mAppBarConfiguration);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
NavController navController = Navigation.findNavController(context, R.id.nav_host_fragment);
return NavigationUI.onNavDestinationSelected(item, navController);
}
});
In your case it is enough since the id in the menu matches with the id in the navigation graph.
In general you can also use:
public boolean onMenuItemClick(MenuItem item) {
Navigation.findNavController(view).navigate(R.id.action...);
//....
}
Final note: the method onCreateOptionsMenu is only triggered if your are using an ActionBar.
For Navigation component you can use inflator
val view-inflater.inflate(R.Layout.fragment_main, container, false)
view.textview1.setonClickListener{
Navigation.findNavController(view).navigate(R.id.settings)
}

java.lang.IllegalStateException: does not have a NavController set on xxxxx(location address) error

I was creating a user home page activity in Android and my app crashes when the app tries to access the UserHome Activity after login. I am not able to figure out why this is happening.
Error
java.lang.IllegalStateException: Activity com.example.commerce.UserHome#xxxxxxx does not have a NavController set on XXXXXXXXXXX
**(X,x denote some alphanumeric addresses)
activity_user_home.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_user_home"
app:menu="#menu/activity_user_home_drawer" />
<include
layout="#layout/app_bar_user_home"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.drawerlayout.widget.DrawerLayout>
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.commerce.ui.home.HomeFragment"
android:label="#string/menu_home"
tools:layout="#layout/fragment_home">
<action
android:id="#+id/action_HomeFragment_to_HomeSecondFragment"
app:destination="#id/nav_home_second" />
</fragment>
<fragment
android:id="#+id/nav_home_second"
android:name="com.example.commerce.ui.home.HomeSecondFragment"
android:label="#string/home_second"
tools:layout="#layout/fragment_home_second">
<action
android:id="#+id/action_HomeSecondFragment_to_HomeFragment"
app:destination="#id/nav_home" />
<argument
android:name="myArg"
app:argType="string" />
</fragment>
<fragment
android:id="#+id/nav_gallery"
android:name="com.example.commerce.ui.gallery.GalleryFragment"
android:label="#string/menu_gallery"
tools:layout="#layout/fragment_gallery" />
<fragment
android:id="#+id/nav_slideshow"
android:name="com.example.commerce.ui.slideshow.SlideshowFragment"
android:label="#string/menu_slideshow"
tools:layout="#layout/fragment_slideshow" />
</navigation>
The OnCreate method from my UserHome Class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_home);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("Home");
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.bringToFront();
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(UserHome.this, R.id.nav_view);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
Can someone please explain what's causing it.
You missed to define your navHostFragment like this:
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="androidx.navigation.fragment.NavHostFragment"
android:id="#+id/nav_host_fragment"
app:navGraph="#navigation/mobile_navigation" />
this fragment is the host fo all your destinations fragments managed by navController,the navController link every id (via menus) to its detination inside the navGraph
hope this help you resolving your issue;

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

Android Studio Swictch-case Instance not working properly

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.");
}

How to set menu to Toolbar in Android

I want use ToolBar instead of ActionBar, but don't show me menu in toolbar!!! i want set menu such as Refresh or Setting buttons in ActionBar.
Toolbar.xml code :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
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="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:navigationContentDescription="#string/abc_action_bar_up_description"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:title="Main Page"
android:gravity="center"/>
MainPage.java code:
public class MainPage extends AppCompatActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("Main Page");
}
toolbar.setSubtitle("Test Subtitle");
toolbar.inflateMenu(R.menu.main_menu);
}
}
main_menu.xml code :
<?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/menu_main_setting"
android:icon="#drawable/ic_settings"
android:orderInCategory="100"
app:showAsAction="always"
android:actionLayout="#layout/toolbar"
android:title="Setting" />
<item
android:id="#+id/menu_main_setting2"
android:icon="#drawable/ic_settings"
android:orderInCategory="200"
app:showAsAction="always"
android:actionLayout="#layout/toolbar"
android:title="Setting" />
</menu>
How to fix this problem and show menu in Toolbar ? thanks all dears <3
just override onCreateOptionsMenu like this in your MainPage.java
#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, menu);
return true;
}
Don't use setSupportActionBar(toolbar)
I don't know why but this works for me.
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
toolbar.setSubtitle("Test Subtitle");
toolbar.inflateMenu(R.menu.main_menu);
For menu item click do this:
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.item1) {
// do something
} else if (item.getItemId() == R.id.filter) {
// do something
} else {
// do something
}
return false;
}
});
Will update the why part of this answer when I find a proper explanation.
Here is a fuller answer as a reference to future visitors. I usually use a support toolbar but it works just as well either way.
1. Make a menu xml
This is going to be in res/menu/main_menu.
Right click the res folder and choose New > Android Resource File.
Type main_menu for the File name.
Choose Menu for the Resource type.
Paste in the following content as a starter.
<?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_add"
android:icon="#drawable/ic_add"
app:showAsAction="ifRoom"
android:title="Add">
</item>
<item
android:id="#+id/action_settings"
app:showAsAction="never"
android:title="Settings">
</item>
</menu>
You can right click res and choose New image asset to create the ic_add icon.
2. Inflate the menu
In your activity add the following method.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
3. Handle menu clicks
Also in your Activity, add the following method:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_add:
addSomething();
return true;
case R.id.action_settings:
startSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Further reading
Android Menu Documentation
You need to override this code in your Activity:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu, this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
and set your toolbar like this:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
You can still use the answer provided using Toolbar.inflateMenu even while using setSupportActionBar(toolbar).
I had a scenario where I had to move toolbar setup functionality into a separate class outside of activity which didn't by-itself know of the event onCreateOptionsMenu.
So, to implement this, all I had to do was wait for Toolbar to be drawn before calling inflateMenu by doing the following:
toolbar.post {
toolbar.inflateMenu(R.menu.my_menu)
}
Might not be considered very clean but still gets the job done.
First way:
In activitymain.xml
<androidx.appcompat.widget.Toolbar
android:id="#+id/maintoolbar"
android:layout_width="match_parent"
android:layout_height="56dp"/>
In MainActivity.java
import androidx.appcompat.widget.Toolbar;
private Toolbar toolbar;
Inside onCreate method-
toolbar=findViewById(R.id.maintoolbar);
setSupportActionBar(toolbar);
Inside your MainActivity class-
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.<your menu xml file name here>,menu);
return super.onCreateOptionsMenu(menu);
}
Second way :
//Remove setSupportActionBar(toolbar) and onCreateOptionmenu.
toolbar=findViewById(R.id.maintoolbar);
toolbar.inflateMenu(R.menu.<your menu xml file name here>);
Also you need this, to implement some action to every options of menu.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_help:
Toast.makeText(this, "This is teh option help", Toast.LENGTH_LONG).show();
break;
default:
break;
}
return true;
}
Without ActionBar but with Toolbar
If you want to use a Toolbar instead of the ActionBar, to setSupportActionBar is contradiction in principle as #RohitSingh answered above.
You need neither to use setSupportActionBar nor to override onCreateOptionsMenu and onOptionsItemSelected which are used for the ActionBar.
NoActionBar theme
Place a Toolbar in the layout xml
Prepare a menu xml
Toolbar#inflateMenu (alternatively you can also set a menu in the layout xml)
Toolbar#setOnMenuItemClickListener
Below is an example.
1. NoActionBar theme
(MaterialCompolent.DayNight theme is used in this sample)
<style name="Theme.AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
2. Place a Toolbar in the layout
(MaterialToobar is used in this sample)
<androidx.constraintlayout.widget.ConstraintLayout
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">
<com.google.android.material.appbar.MaterialToolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
3. Prepare a menu xml
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/item1"
android:title="#string/item1"
app:showAsAction="ifRoom" />
<item
android:id="#+id/item2"
android:title="#string/item2"
app:showAsAction="ifRoom" />
</menu>
4. Toolbar#inflateMenu
binding.toolbar.inflateMenu(R.menu.main); // binding is a ViewBinding
5. Toolbar#setOnMenuItemClickListener
Recent Android recommend to avoid to use switch to differentiate ids. Using a normal if ~ else if ~ else block is desirable. In addition to that, we can use lambda in Java 8.
binding.toolbar.setOnMenuItemClickListener(menuItem -> {
int itemId = menuItem.getItemId();
if (itemId == R.id.item1) {
// do something for item1
return true;
} else if (itemId == R.id.item2) {
// do something for item2
return true;
} else {
// if you do nothing, returning false should be appropriate.
return false;
}
});
Although I agree with this answer, as it has fewer lines of code and that it works:
How to set menu to Toolbar in Android
My suggestion would be to always start any project using the Android Studio Wizard. In that code you will find some styles:-
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
and usage is:
<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>
Due to no action bar theme declared in styles.xml, that is applied to the Main Activityin the AndroidManifest.xml, there are no exceptions, so you have to check it there.
<activity android:name=".MainActivity" android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
The Toolbar is not an independent entity, it is always a child
view in AppBarLayout that again is the child of
CoordinatorLayout.
The code for creating a menu is the standard code since day one,
that is repeated again and again in all the answers, particularly
the marked one, but nobody realized what is the difference.
BOTH:
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
AND:
How to set menu to Toolbar in Android
WILL WORK.
Happy Coding :-)
In XML add one line inside
<com.google.android.material.appbar.MaterialToolbar app:menu="#menu/main_menu"/>
In java file
Remove three line setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setTitle("Main Page"); }
add one line toolbar.setTitle("Main Page")
In your activity override this method.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
This will inflate your menu below:
<?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/menu_main_setting"
android:icon="#drawable/ic_settings"
android:orderInCategory="100"
app:showAsAction="always"
android:actionLayout="#layout/toolbar"
android:title="Setting" />
<item
android:id="#+id/menu_main_setting2"
android:icon="#drawable/ic_settings"
android:orderInCategory="200"
app:showAsAction="always"
android:actionLayout="#layout/toolbar"
android:title="Setting" />
</menu>
In my case, I'm using an AppBarLayout with a CollapsingToolbarLayout and the menu was always
being scrolled out of the screen, I solved my problem by switching android:actionLayout in menu's XML to
the toolbar's id. I hope it can help people in the same situation!
activity_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:fab="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.MainScreenActivity"
android:screenOrientation="portrait">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="300dp"
app:elevation="0dp"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsingBar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="exitUntilCollapsed|scroll"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginStart="48dp"
app:expandedTitleMarginEnd="48dp"
>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:elevation="0dp"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:layout_collapseMode="pin"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
main_menu.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/logoutMenu"
android:orderInCategory="100"
android:title="#string/log_out"
app:showAsAction="never"
android:actionLayout="#id/toolbar"/>
<item
android:id="#+id/sortMenu"
android:orderInCategory="100"
android:title="#string/sort"
app:showAsAction="never"/> </menu>
You can achieve this by two methods
Using XML
Using java
Using XML
Add this attribute to toolbar XML
app:menu = "menu_name"
Using java
By overriding onCreateOptionMenu(Menu menu)
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.demo_menu,menu);
return super.onCreateOptionsMenu(menu);
}
}
for more details or implementating click on the menu go through this article
https://bedevelopers.tech/android-toolbar-implementation-using-android-studio/
You don't actually need to touch the fragment/activity class at all to get a menu inside a toolbar. You can use Rohit Singh's method inside onViewCreated method
import androidx.appcompat.widget.Toolbar
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val toolbar = view.findViewById<Toolbar>(R.id.inbox_toolbar)
toolbar.inflateMenu(R.menu.inbox_menu)
}
or
simply define a app:menu element inside the toolbar,
<androidx.appcompat.widget.Toolbar ...
app:menu= "#menu/myMenu" ?>
Simple fix to this was setting showAsAction to always in menu.xml in res/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">
<item
android:id="#+id/add_alarm"
android:icon="#drawable/ic_action_name"
android:orderInCategory="100"
android:title="Add"
app:showAsAction="always"
android:visible="true"/>
</menu>
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar;
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_drawer,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_drawer){
drawerLayout.openDrawer(GravityCompat.END);
if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
drawerLayout.closeDrawer(GravityCompat.END);
} else {
drawerLayout.openDrawer(GravityCompat.END);
}
}
return super.onOptionsItemSelected(item);
}
res/layout/drawer_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">
<item
android:id="#+id/action_drawer"
android:title="#string/app_name"
android:icon="#drawable/ic_menu_black_24dp"
app:showAsAction="always"/>
</menu>
toolbar.xml
<com.google.android.material.appbar.AppBarLayout
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="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"
app:titleTextColor="#android:color/white"
app:titleTextAppearance="#style/TextAppearance.Widget.Event.Toolbar.Title">
<TextView
android:id="#+id/toolbar_title"
android:layout_gravity="center"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/app_name"
android:textColor="#android:color/white"
style="#style/TextAppearance.AppCompat.Widget.ActionBar.Title" />
</androidx.appcompat.widget.Toolbar>
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.my_toolbar);
*// here is where you set it to show on the toolbar*
setSupportActionBar(toolbar);
}
Well, you need to set support action bar setSupportActionBar(); and pass your variable, like so: setSupportActionBar(toolbar);

Categories

Resources