Disclaimer: I already read the post at onClick event in navigation drawer, but sadly it does not work for me.
I am pretty new to Android I am just making my first app in Kotlin and I wanted to integrate an NavigationDrawer. In it I have integrated an option "Website" which should just launch a website. Just when I click on it it closes the drawer, but does not start the Intent for the website.
My Code: (I removed unimportant parts that are needed for the rest of the app)
MainActivity.kt:
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
private lateinit var drawerLayout: DrawerLayout
private lateinit var aToggle: ActionBarDrawerToggle
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activity_main)
createNotificationChannel()
setNavigationViewListener()
val toolbar: Toolbar = toolbar
setSupportActionBar(toolbar)
val actionbar: ActionBar? = supportActionBar
actionbar?.apply {
setDisplayHomeAsUpEnabled(true)
setHomeAsUpIndicator(R.drawable.ic_menu)
}
drawerLayout = drawer_layout
aToggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close)
drawerLayout.addDrawerListener(aToggle)
drawerLayout.addDrawerListener(
object : DrawerLayout.DrawerListener {
override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
}
override fun onDrawerOpened(drawerView: View) {
}
override fun onDrawerClosed(drawerView: View) {
}
override fun onDrawerStateChanged(newState: Int) {
}
}
)
aToggle.syncState()
val navigationView: NavigationView = findViewById(R.id.nav_view)
navigationView.setNavigationItemSelectedListener { menuItem ->
// set item as selected to persist highlight
menuItem.isChecked = true
// close drawer when item is tapped
drawerLayout.closeDrawers()
// Add code here to update the UI based on the item selected
// For example, swap UI fragments here
true
}
}
private fun setNavigationViewListener() {
val navigationView = nav_view
navigationView.setNavigationItemSelectedListener(this)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.drawer_view, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
drawerLayout.openDrawer(GravityCompat.START)
true
}
else -> super.onOptionsItemSelected(item)
}
if(aToggle.onOptionsItemSelected(item)) {
return true
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.website -> {
val i = Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://gym-wen.de/vp/"))
startActivity(i)
drawerLayout.closeDrawer(GravityCompat.START)
return true
}
else -> {}
}
return true
}
}
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:layout_width="match_parent"
android:id="#+id/drawer_layout"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar" />
<ListView
android:id="#+id/vertretungs_list"
android:paddingTop="?attr/actionBarSize"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>
<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:menu="#menu/drawer_view" />
drawer_view.xml (menu):
<?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/website"
android:title="#string/website" />
<item
android:id="#+id/nav_gallery"
android:title="2" />
<item
android:id="#+id/nav_slideshow"
android:title="3" />
<item
android:id="#+id/nav_manage"
android:title="4" />
</group>
I am pretty sure I forgot something, but I just do not know what it is. I read many tutorials and other posts, but I just do not know it. Hopefully someone can help me :)
Greetings
You have set two listeners for the same things. One overwrites the other.
navigationView.setNavigationItemSelectedListener { menuItem ->
// set item as selected to persist highlight
menuItem.isChecked = true
// close drawer when item is tapped
drawerLayout.closeDrawers()
// Add code here to update the UI based on the item selected
// For example, swap UI fragments here
true
}
Which does not launch the website and navigationView.setNavigationItemSelectedListener(this) which should.
I were you I would remove the entire first block and implement everything in override fun onOptionsItemSelected(item: MenuItem): Boolean
Your activity class implements NavigationView.OnNavigationItemSelectedListener,
so instead of setting as a listener:
navigationView.setNavigationItemSelectedListener { menuItem ->
// set item as selected to persist highlight
menuItem.isChecked = true
// close drawer when item is tapped
drawerLayout.closeDrawers()
// Add code here to update the UI based on the item selected
// For example, swap UI fragments here
true
}
you should call:
navigationView.setNavigationItemSelectedListener(this)
so this method is called:
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.website -> {
val i = Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://gym-wen.de/vp/"))
startActivity(i)
drawerLayout.closeDrawer(GravityCompat.START)
return true
}
else -> {}
}
return true
}
and in this method you manipulate the closing of the drawer or the checked items.
Related
I'm new in Android Studio and having trouble opening fragment on click CardView in other fragment. I have Navigation View in layout and navigate to other fragment (fragment_home, fragment_gallery, fragment_slideshow, and other fragment layout.). But I have to create CardView in fragment_home to click for open some fragment layout (Gallery and Slideshow).
I have layout:
1. fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.home.HomeFragment">
<androidx.cardview.widget.CardView
android:id="#+id/cardOpenGallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_margin="20dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="#ccc">
<TextView
android:id="#+id/textOpenGallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:textAlignment="center"
android:textSize="30sp"
android:textColor="#000"
android:text="Open Gallery"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
2. fragment_gallery.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".ui.gallery.GalleryFragment">
<!-- other layout element here -->
</FrameLayout>
3. fragment_slideshow.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".ui.gallery.SlideshowFragment">
<!-- other layout element here -->
</FrameLayout>
And Kotlin code,
1. MainActivity.kt
import ...
class MainActivity : AppCompatActivity() {
private lateinit var appBarConfiguration: AppBarConfiguration
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
val fab: FloatingActionButton = findViewById(R.id.fab)
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
val navView: NavigationView = findViewById(R.id.nav_view)
val navController = findNavController(R.id.nav_host_fragment)
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = AppBarConfiguration(setOf(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow), drawerLayout)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment)
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
}
2. HomeFragment.kt
import ...
class HomeFragment : Fragment() {
private lateinit var homeViewModel: HomeViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
homeViewModel =
ViewModelProviders.of(this).get(HomeViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_home, container, false)
//I have problem here-----
val myCard1 = root.findViewById(R.id.cardOpenGallery) as CardView
myCard1.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
inflater.inflate(R.layout.fragment_gallery, container, false)
}
})
return root
}
}
3. GalleryFragment.kt
import ...
class GalleryFragment : Fragment() {
private lateinit var galleryViewModel: GalleryViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
galleryViewModel =
ViewModelProviders.of(this).get(GalleryViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_gallery, container, false)
val textView: TextView = root.findViewById(R.id.text_gallery)
galleryViewModel.text.observe(viewLifecycleOwner, Observer {
textView.text = it
})
return root
}
}
4. SlideshowFragment.kt
import ...
class SlideshowFragment : Fragment() {
private lateinit var slideshowViewModel: SlideshowViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
slideshowViewModel =
ViewModelProviders.of(this).get(SlideshowViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_slideshow, container, false)
val textView: TextView = root.findViewById(R.id.text_slideshow)
slideshowViewModel.text.observe(viewLifecycleOwner, Observer {
textView.text = it
})
return root
}
}
How to implement action for CardView click to open other fragment?, Please help and Thank for your any solution. Thanks.
You need to open another fragment here. For this you need to replace the fragment container in MainActivity with the desired fragment.
Replace this
myCard1.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
inflater.inflate(R.layout.fragment_gallery, container, false)
}
})
with this
myCard1.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
((Activity) getContext).supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, GalleryFragment())
.commit()
}
})
I hope this will work for you.
Happy Coding :)
You're just trying to inflate the fragment_gallery inside your homeFragment. I don't think it's the right way to do it. Although, I'll suggest the approach I use.
Inside your activity_main.xml add the FrameLayout. which will be useful to add/replace the desired fragment into it.
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Now in your Activity, create the following function. It will help you to replace the desired fragment.
private fun replaceFragment(fragmentInstance: Fragment) {
supportFragmentManager
.beginTransaction()
.addToBackStack(fragmentInstance.javaClass.canonicalName)//optional
.replace(R.id.container, fragmentInstance)
.commit()
}
Now, inside onCreate load the homeFragment (as it is your first fragment to show)
override fun onCreate(savedInstanceState: Bundle?) {
val fragment = HomeFragment()
replaceFragment(fragment)
}
At this stage, you'll be able to load homeFragment successfully. Now next step is to create a callback interface. Every time you click on any card from the homeFragment you just have to provide the required information back to the mainActivity. It is good practice to leaving the responsibility of loading fragments on the activity.
interface OnCardClickListener {
fun onCardClick(fragment: Fragment)
}
implement this listener in MainActivity.
class MainActivity: OnCardClickListener{
It will override the onCardClick. now inside onCardClick call the replace method.
override onCardClick(fragment: Fragment){
replaceFragment(fragment)
}
Inside HomeFragment, Create an instance of OnCardClickListener
var listener: OnCardClickListener? = null
then in onAttach.
override fun onAttach(context: Context) {
super.onAttach(context)
listener = context as OnCardClickListener
}
Till this point, we have implemented the mechanism required to load fragment. Now only one final step is pending which is opening the desired fragment onClick of cardView. for that do as follow:
myCard1.setOnClickListener{
listener.onCardClick(GalleryFragment())
}
//If there's one more card available.
myCard2.setOnClickListener{
listener.onCardClick(SlideshowFragment())
}
I am trying to implement search functionality into an android app using the Search Dialog. After following the documentation, I got this search dialog when pressing the search button in my app.
As you can see, the search dialog is too small( the app bar can be seen below it), it is not centered, and contains the app icon near the back button.
The Search Dialog showed in the guide is centered vertically in the app bar and doesn't have the app icon near the back button, which is what I want to do for my search dialog as well. But I can't seem to find any resource on how to do it. Can anyone help me out?
Thanks in advance!
Edit: Here is the code that enables the Search Dialog
MainActivity.kt
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val root = binding.root
setContentView(root)
//Setup the app bar
setSupportActionBar(binding.toolbar);
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val inflater = menuInflater;
inflater.inflate(R.menu.app_bar_menu, menu)
return true;
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.action_search -> {
onSearchRequested()
true
}
else -> {
super.onOptionsItemSelected(item)
}
}
}
searchable.xml
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="#string/search_hint"
android:label="#string/app_name">
</searchable>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:title="#string/app_name" />
</androidx.constraintlayout.widget.ConstraintLayout>
Using the method that you want for create a search dialog, this is the most similar aspect that it can achieve:
https://i.stack.imgur.com/hwTlF.png
This is the code that I implemented:
MainActivity.class code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#SuppressLint("ResourceType")
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(true);
searchView.setIconified(false);
//Here you can set the parameters of the search view
return true;
}
I created a menu resource file called options_menu.xml and that's the code:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/search"
android:title="title"
android:icon="#drawable/search_icon"
app:showAsAction="collapseActionView|ifRoom"
app:actionViewClass="android.widget.SearchView" />
</menu>
And the searchable xml file called search.xml
<?xml version="1.0" encoding="utf-8"?>
<Searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="Your hint"
android:label="Label text">
</Searchable>
I created the icon of the menu in the drawable folder but you can change to other icon if you want.
Also I leave several links to all the customizations that you can add to the searchView:
https://developer.android.com/guide/topics/search/searchable-config
https://developer.android.com/reference/android/widget/SearchView
I hope this is the right solution for you.
I made a different search method, I used the Android Studio search view,
that's the main activity code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.mySearchButton);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
You have to create an Android Resource File, select resource type "menu", and call it as you want, after that, add this item:
<item android:id="#+id/mySearchButton"
android:title="Button"
android:icon="#drawable/search_icon"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="always"/>
This code worked for me, images here:
https://i.stack.imgur.com/XNRZy.png
https://i.stack.imgur.com/hUt4x.png
I hope it works for you aswell.
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)
}
}
I have a button in my OptionMenu which when touched will open a popup menu of items which are fetched at run time and added programmatically (so can't use hard coded xml menu items). I want to highlight a subset of these items according to their value, I used what is suggested here: How to customize item background and item text color inside NavigationView? to try and get the items to be colored differently. However, all of the items are colored the same despite the isChecked() value being different.
Here is a small working example of the issue:
MainActivity.java
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.actionbar_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id) {
case R.id.action_bar_button:{
showMenu();
return true;
}
}
return super.onOptionsItemSelected(item);
}
private void showMenu() {
View v = findViewById(R.id.action_bar_button);
Context wrapper = new ContextThemeWrapper(this, R.style.MyPopupMenu);
PopupMenu popupMenu = new PopupMenu(wrapper, v);
//Sample items to demonstrate the issue. I want the background to be red if false, blue if true
Map<String, Boolean> list = new HashMap<>();
list.put("Item 1", true);
list.put("Item 2", false);
list.put("Item 3", true);
for(Map.Entry<String, Boolean> entry : list.entrySet()){
String msg = entry.getKey();
MenuItem item = popupMenu.getMenu().add(msg).setCheckable(true).setChecked(entry.getValue());
System.out.println(item.getTitle() + ": " + item.isChecked());
}
popupMenu.show();
}
styles.xml contains:
<style name="MyPopupMenu" parent="Widget.AppCompat.PopupMenu">
<item name="android:itemBackground">#drawable/menu_item_background</item>
</style>
actionbar_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/action_bar_button"
android:title="List"
android:icon="#drawable/ic_launcher_foreground"
app:showAsAction="always" />
</menu>
colors.xml contains:
<color name="red">#ff0000</color>
<color name="blue">#0000FF</color>
And the menu_item_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/blue" android:state_checked="true"/>
<item android:drawable="#color/red" android:state_checked="false"/>
</selector>
However, when I run this I get the following:
As you can see although the isChecked state of Item 1 and 3 is true, they still appear red. The logcat output confirms this.
As an experiment I changed the menu_item_background.xml to use the android:state_enabled instead of checked and it works as expected:
What's going on here? Why doesn't this work with android:state_checked?
Thanks for your help.
If your main motive is to highlight the selected item or similar kind of problem.
I would like to suggest as one of the solutions which worked for me to use spinner, which Popup Menu provides a similar dropdown option as Spinner, with a custom layout for dropdown, and change the background color at getDropDownView() at the adapter for the spinner.
R.layout.spinner_item.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_context"
android:layout_height="wrap_content"
android:visibility="gone"
/>
R.layout.spinner_drop_down.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
>
<TextView
style="?android:attr/spinnerDropDownItemStyle"
android:singleLine="true"
android:layout_width="wrap_content"
android:layout_height="?attr/dropdownListPreferredItemHeight"
android:id="#+id/spinner_dropdown_text"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"/>
</LinearLayout>
UI Design
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<!--Some Layouts-->
<Spinner
android:id="#+id/spinner"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity="center_vertical"
android:background="#drawable/icon"
android:gravity="center"
android:textDirection="firstStrongLtr"
android:overlapAnchor="false"/>
<!--Some More Layouts-->
</LinearLayout>
MainActivity.kt
val spinner = findViewById<Spinner>(R.id.spinner)
val spinnerData = arrayListOf<String>("Item 1", "Item 2", "Item 3")
val arrayAdapter = object : ArrayAdapter<String>(activity!!.applicationContext,R.layout.spinner_item, spinnerData) {
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
val spinnerItem = layoutInflater.inflate(R.layout.spinner_drop_down, null)
val dropDownText = spinnerItem.findViewById<TextView>(R.id.spinner_dropdown_text)
dropDownText.text = spinnerData[position]
val selected = spinner.selectedItemPosition
if (position == selected) spinnerItem.setBackgroundColor(Color.GRAY)
return spinnerItem
}
}
arrayAdapter.setDropDownViewResource(R.layout.spinner_drop_down)
spinner.adapter = arrayAdapter
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
//Do whatever you want to do when Item selected
}
override fun onNothingSelected(parent: AdapterView<*>) {
//Do whatever you want to do when No Item selected
}
}
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);