ToolBar menu item click in a fragment (Kotlin) - android

In my app, i have an Activity, which has a FrameLayout in it. In this FrameLayout, there is a fragment, containing a ToolBar and a RecyclerView.
In this toolbar, i have a search button, which should start an Activity on item click. However, when i try to use onOptionsItemSelected, the apps gets built and installed succesfully, but when i try to tap that button in question, nothing happens. The Logcat, doesnt say anything either.
Can some points me what im doing wrong? Are there simpler or other easy ways to manage on ToolBar item clicks?
Fragment.kt
class FragmentTrack : Fragment() {
...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? = inflater.inflate(R.layout.fragment_track, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
...
topToolbar.setNavigationOnClickListener {
val dialog = FragmentBottomSheetDrawer()
dialog.show(childFragmentManager, dialog.tag)
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_toolbar, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId) {
R.id.fsvSearch -> Toast.makeText(context, "Clicked search button", Toast.LENGTH_SHORT).show()
}
return true
}
}
fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:theme="#style/Theme.Design.NoActionBar">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/topToolbar"
android:background="#color/colorPrimaryDark"
app:navigationIcon="#drawable/ic_outline_menu_24"
app:popupTheme="#style/popupMenuThemeDark"
app:titleTextColor="#android:color/white"
app:title="Revo"
app:menu="#menu/menu_toolbar"
app:layout_scrollFlags="scroll|enterAlways" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvTracks"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:clipToPadding="false"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
toolbar_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/fsvSearch"
android:icon="#drawable/ic_search_24px"
android:title="#string/search"
app:showAsAction="always"/>
<item
android:id="#+id/fsvOrder"
android:icon="#drawable/ic_sort_24px"
android:title="#string/sort"
app:showAsAction="ifRoom">
<menu>
<group android:id="#+id/sortMenu" android:checkableBehavior="single">
<item
android:id="#+id/sortIncrease"
android:title="#string/increasing"/>
<item
android:id="#+id/sortDecrease"
android:title="#string/decreasing"/>
<item
android:id="#+id/sortMArtist"
android:title="#string/artist"/>
<item
android:id="#+id/sortAlbum"
android:title="#string/albums"/>
<item
android:id="#+id/sortYear"
android:title="#string/year"/>
<item
android:id="#+id/sortDate"
android:title="#string/date"/>
</group>
</menu>
</item>
<item
android:id="#+id/fsvGrid"
android:icon="#drawable/ic_grid_on_24px"
android:title="#string/grid"
app:showAsAction="ifRoom">
<menu>
<group android:id="#+id/gridMenu" android:checkableBehavior="single">
<item
android:id="#+id/gridOne"
android:title="1"/>
<item
android:id="#+id/gridTwo"
android:title="2"/>
<item
android:id="#+id/gridThree"
android:title="3"/>
<item
android:id="#+id/gridFour"
android:title="4"/>
</group>
</menu>
</item>
</menu>

I found a solution thanks to some external help. Its possible to work on the Toolbars item in an easier way.
In the onViewCreated method, we must add:
topToolbar.inflateMenu(R.menu.menu_toolbar)
topToolbar.setOnMenuItemClickListener {
when(it.itemId) {
R.id.fsvSearch -> //your code
}
true
}
Also, if the menu gets duplicated, remove the app:menu tag in the Toolbars xml

thanks Meltix for this, I've done a lot of research but most of the posts in SO are about Java and old fashioned ActionBar. There is not much info about material ToolBar and kotlin examples.
In my case I'm working on an old app developed mostly in Java but now developing new functionalities in Kotlin. In my fragment, I wasn't able to change the ActionBar's icons and behaviour (I wanted a particular ActionBar for my fragment). The solution I found is to hide the ActionBar and create a Toolbar inflating a custom menu inside. Also I added a back arrow button (thanks to John: here).
I've came to the conclusion (maybe I'm wrong) that you can't manage ActionBars from kotlin fragments, that's why you have to use toolbars. Here is my code in case it can help someone.
MyFragment.kt
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// hide the old actionBar
(activity as AppCompatActivity).supportActionBar!!.hide()
// create the toolbar
val toolbar = binding?.myToolbar
// add the back arrow button, see function below
val resId = getResIdFromAttribute(toolbar.context, android.R.attr.homeAsUpIndicator)
toolbar.navigationIcon = ContextCompat.getDrawable(toolbar.context, resId)
// tapping on the arrow will pop the current fragment
toolbar.setNavigationOnClickListener { parentFragmentManager?.popBackStackImmediate() }
// change toolbar title
toolbar.title = "Some title"
// inflate a custom menu, see code below
toolbar.inflateMenu(R.menu.my_custom_menu)
toolbar.setOnMenuItemClickListener {
when (it.itemId) {
R.id.infoButton -> someAction()
}
true
}
}
// get back arrow icon
#AnyRes
fun getResIdFromAttribute(context: Context, #AttrRes attr: Int): Int {
if (attr == 0) return 0
val typedValueAttr = TypedValue()
context.theme.resolveAttribute(attr, typedValueAttr, true)
return typedValueAttr.resourceId
}
my_fragment.xml
...
<androidx.appcompat.widget.Toolbar
android:id="#+id/myToolBar"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:visibility="visible"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:background="#color/azulOscuro"
>
</androidx.appcompat.widget.Toolbar>
my_custom_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:jsmovil="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<item
android:id="#+id/infoButton"
android:icon="#drawable/ic_info_blanco"
android:title="#string/tutorial"
android:textColor="#color/blanco"
jsmovil:showAsAction="always"
/>
</menu>
Result

Related

Android NAvigation with BottomNavigationView does not save UI state

I have a Fragment with bottom tabs named TabsFragment
class BottomTabsFragment : Fragment(R.layout.fragment_tabs) {
private val bottomNavigationView: BottomNavigationView by lazy {
requireView().findViewById(R.id.bottom_navigation_view)
}
private val tabsNavigation: NavController by lazy {
(childFragmentManager.findFragmentById(R.id.tabs_host_fragment) as NavHostFragment).navController
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
bottomNavigationView.setupWithNavController(tabsNavigation)
}
}
Here is a menu for bottom navigation view:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#id/dashboard_navigation"
android:title="Dashboard" />
<item
android:id="#id/search_vehicle_navigation"
android:title="Search" />
<item
android:id="#id/todos_navigation"
android:title="Todos" />
<item
android:id="#id/activities_navigation"
android:title="Activities" />
<item
android:id="#id/more_navigation"
android:title="More" />
</menu>
Graph for bottom menu:
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/tabs_navigation"
app:startDestination="#id/search_vehicle_navigation">
<include app:graph="#navigation/dashboard_navigation" />
<include app:graph="#navigation/search_vehicle_navigation" />
<include app:graph="#navigation/todos_navigation" />
<include app:graph="#navigation/activities_navigation" />
<include app:graph="#navigation/more_navigation" />
</navigation>
Everything is done according Google tutorials and samples and it does not work. Only 1 default fragment that is setted as StartDestination is saved (Becouse it is in stack to be displayed when user press back button):
https://developer.android.com/guide/navigation/navigation-multi-module
https://github.com/android/architecture-components-samples/tree/main/NavigationAdvancedSample

Can't show/hide menu items on Kotlin - Android Studio

my application has a menu of 3 options, and what I want is that according to a condition that I define, it shows only 2 options, or it shows 3.
I have tried all the options that I have found on google and here, but none have worked for me.
My idea is that as soon as the view is created, the menu already shows the options that it can show according to the condition. But as I have been able to achieve it, I added a button to simulate the event.
I would greatly appreciate your help.
Here I attach the code:
1) activity_home.xml (some part)
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:onClick="ActivarMenus"/>
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:menu="#menu/home_menu"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" >
2) Aqui el archivo home_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menu_item"
android:icon="#drawable/ic_baseline_more_vert_24"
app:showAsAction="ifRoom"
tools:ignore="MenuTitle">
<menu>
<item
android:id="#+id/newRegister"
android:icon="#drawable/ic_baseline_add_24"
app:showAsAction="always"
android:visible="true"
android:title="Nueva Orden Swab" />
<item
android:id="#+id/newAnexoo"
android:icon="#drawable/ic_baseline_add_24"
app:showAsAction="always"
android:visible="true"
android:title="Nuevo Formulario Anexo O" />
<item
android:id="#+id/sync"
android:icon="#drawable/ic_baseline_sync_24"
app:showAsAction="always"
android:visible="true"
android:title="Sincronizar" />
</menu>
</item>
</menu>
3) And a part of the HomeActivity.kt
class HomeActivity : ActivityViewBinding<ActivityHomeBinding, HomeVM>() {
private var mainMenu: Menu? = null
private lateinit var spm : SharedPreferencesManager
private val adapter: OrderAdapter by inject()
override fun inflateLayout(layoutInflater: LayoutInflater) =
ActivityHomeBinding.inflate(layoutInflater)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
//MenuMain.findItem(R.id.newAnexoo).isVisible = true
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater: MenuInflater = menuInflater
inflater.inflate(R.menu.home_menu, menu)
mainMenu = menu;
return true
}
fun ActivarMenus(view: View) {
mainMenu?.findItem(R.id.newRegister)?.isVisible = true
}
You should try this one it might be work.
if you want to change Menu Items at Run time You can use onPrepareOptionsMenu
#Override
public boolean onPrepareOptionsMenu(Menu menu){
if (//Your condition) {
menu.findItem(R.id.newRegister).setVisible(true);
}else {
menu.findItem(R.id.newRegister).setVisible(false);
}
return true;
}

Weird in popup menu

I have created a menu icon on action bar. When it is clicked, I expect it will show something like this
But it display on the left hand side instead.
What could be this issue ?
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater!!.inflate(R.menu.fragment_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.getItemId()
if (id == R.id.more) {
var popup: PopupMenu? = PopupMenu(context!!, view!!)
popup?.menuInflater?.inflate(R.menu.pop_up_menu, popup.menu)
popup?.show()
popup?.setOnMenuItemClickListener({ item: MenuItem? ->
when (item!!.itemId) {
R.id.logOut -> {
}
}
true
})
} else
super.onOptionsItemSelected(item)
return true
}
fragment_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/more"
android:title="menu"
app:showAsAction="always"
android:icon="#drawable/ic_more"/>
</menu>
pop_up_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/logOut"
app:showAsAction="always"
android:title="Log Out"
/>
</menu>
The view I passing is this
#Nullable
public View getView() {
return this.mView;
}
You are passing the wrong view as what #CodeRed mentioned.
Replace
var popup: PopupMenu? = PopupMenu(context!!, view!!)
to
val vItem = getActivity().findViewById<View>(R.id.more)
var popup: PopupMenu? = PopupMenu(context!!, vItem)
Menu in ActionBar is populated automatically by system, you don't need to write code to populate it.
To achieve the menu like figure 1, fragment_menu should be like:
<menu>
<item android:title="Search" />
<item android:title="Locate" />
<item android:title="Refresh" />
<item android:title="Help" />
<item android:title="Check for update" />
</menu>
onOptionItemSelected is used to handle when above menu is clicked, not used to show the menu.
popup menu is free position menu like right click menus in windows, not the one you expect in figure 1.

Navigation drawer menu item click no response

I am developing an android app and am new to programming. I have extended the base drawer activity to all activity. But after I clicked the menu button of the drawer in the activities that extend drawer activity, nothing happened. Below is my code in the base drawer activity.
open class DrawerActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.requestWindowFeature(Window.FEATURE_NO_TITLE)
this.window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
setContentView(R.layout.activity_drawer)
setSupportActionBar(toolbar)
nav_view.setNavigationItemSelectedListener(this)
pageToGo = 1
println("PageToGo on start activity: $pageToGo")
}
override fun onBackPressed() {
println("Back is pressed")
if (drawer_layout.isDrawerOpen(GravityCompat.END)) {
drawer_layout.closeDrawer(GravityCompat.END)
} else {
finishAffinity()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.drawer, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// 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.
when (item.itemId) {
R.id.action_settings -> return true
else -> return super.onOptionsItemSelected(item)
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
when (item.itemId) {
R.id.nav_show_stat -> {
println("I am clicked")
}
R.id.nav_restart_game -> {
}
R.id.nav_achievements -> {
}
R.id.nav_settings -> {
}
R.id.nav_about_us -> {
}
R.id.nav_contact_us -> {
}
}
drawer_layout.closeDrawer(GravityCompat.END)
return true
}
override fun setContentView(layoutResID:Int) {
val fullLayout: DrawerLayout
val actContent: FrameLayout
fullLayout = layoutInflater.inflate(R.layout.activity_drawer, null) as DrawerLayout
actContent = fullLayout.findViewById(R.id.act_content) as FrameLayout
layoutInflater.inflate(layoutResID, actContent, true)
super.setContentView(fullLayout)
}
Below is my drawer_layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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="end">
<include
layout="#layout/app_bar_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<FrameLayout
android:id="#+id/act_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="end"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_drawer"
app:menu="#menu/activity_drawer_drawer">
</android.support.design.widget.NavigationView>
Below is my menu code
<?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_show_stat"
android:icon="#drawable/ic_menu_camera"
android:title="#string/nav_show_stat" />
<item
android:id="#+id/nav_restart_game"
android:icon="#drawable/ic_menu_gallery"
android:title="#string/nav_restart" />
<item
android:id="#+id/nav_achievements"
android:icon="#drawable/ic_menu_slideshow"
android:title="#string/nav_achievements" />
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_menu_manage"
android:title="#string/nav_settings" />
</group>
<item android:title="#string/nav_our_company">
<menu>
<item
android:id="#+id/nav_about_us"
android:icon="#drawable/ic_menu_share"
android:title="#string/nav_about_us" />
<item
android:id="#+id/nav_contact_us"
android:icon="#drawable/ic_menu_send"
android:title="#string/nav_contact_us" />
</menu>
</item>
Below is my code in main activity
class MainActivity : DrawerActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
load()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
beginAdventure()
main_layout.setOnTouchListener(object : OnSwipeTouchListener(applicationContext) {
override fun onSwipeLeft() {
drawer_layout.openDrawer(GravityCompat.END)
}
})
}
private fun beginAdventure() {
start_game_btn.setSafeOnClickListener {
nextPage("ChapterOneActOneActivity", 1)
}
}
}
I know I am missing something important. But I just don't know what it is. The onNavigationItemSelected seems not working because when I click on R.id.nav_show_stat, "I am clicked" never gets printed. Please kindly let me know what I should do to make the drawer buttons work in all activity. Thank you in advance.
Edit2: my drawer in main activity
https://imgur.com/a/ofGzncZ
So when I click on Show Statistics, the "I am clicked" is never printed. How do I handle the click event to do what I want?
No need to use the below given code separately :-
override fun setContentView(layoutResID:Int) {
val fullLayout: DrawerLayout
val actContent: FrameLayout
fullLayout = layoutInflater.inflate(R.layout.activity_drawer, null) as DrawerLayout
actContent = fullLayout.findViewById(R.id.act_content) as FrameLayout
layoutInflater.inflate(layoutResID, actContent, true)
super.setContentView(fullLayout)
}
just add :-
setContentView(R.layout.your_layout_filename);
i think there is no other issue in your code

Toolbar menu icon not display

I know may be duplicate but i am not finding any solution for that.
Actually, i want to show menu with text and icon inside fragment which having a toolbar, i have just add one line in fragment to show menu is
class JustTry : Fragment(){
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.fragment_try, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
var mToolbar = view!!.findViewById<Toolbar>(R.id.toolbar)
mToolbar.inflateMenu(R.menu.dashboard_menu)
}
}
I got this output from this code.
here is my 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/nav_home"
android:icon="#mipmap/ic_launcher"
android:title="Home" />
<item
android:id="#+id/nav_messages"
android:icon="#mipmap/ic_launcher"
android:title="Messages" />
</menu>
My question is why i am not getting Icon in Message and Home items even i am adding android:icon tag.
Any help will be appreciated.
You can try
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:balloonberry="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menu_item"
android:icon="#drawable/img_menu"
balloonberry:showAsAction="always">
<menu>
<item
android:id="#+id/btn_delete"
android:title="delete"
android:icon="#android:drawable/ic_delete"/>
<item
android:id="#+id/btn_message"
android:title="Message"
android:icon="#android:drawable/ic_dialog_alert"/>
</menu>
</item>
</menu>

Categories

Resources