Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

xml - Android add individual menu item ActionListener

I made an Android app that have a top menu from the navigation drawable with 2 items, that are two vectors images, one to make a filter and one to add something. Reading the codelabs i have to override the 2 methods onCreateOptionsMenu (that put the menu in the fragment) and onOptionsItemSelected that is the "action listener". I don't undertand how to perform my actions to each item, so one open the fragment to the filter and the other one to open the fragment to add something. Can someone explain me how to do it? It is correct what i'm doing? i want different toolbar for each fragment, with costum buttons on each toolbar

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater){
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.ticket_menu, menu)
}

override fun onOptionsItemSelected(item: MenuItem) : Boolean{
//the action to make when an items is clicked
return true;
}

my menu xml

<menu //with xmls and attributes>
<item>
     android:id="@+id/filter"
     android:icon="@drawable/ic_filter"
     android:title:"@string/filter_text"
     android:showAsAction="ifRoom"/>
<item>
     android:id="@+id/add"
     android:icon="@drawable/ic_add"
     android:title:"@string/add_text"
     android:showAsAction="ifRoom"/>

</menu> 
question from:https://stackoverflow.com/questions/66064401/android-add-individual-menu-item-actionlistener

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You just need to get the id of the item:

override fun onOptionsItemSelected ( item: MenuItem ): Boolean {
    when ( item.itemId ) {
        R.id.filter -> {
            // perform action here
        }
        R.id.add -> {
            // perform action here
        }
    }
    return super.onOptionsItemSelected ( item )
}

And just create a new menu for the next fragment and follow the same process.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...