Issue
I'm trying to use the following xml to inflate my toolbar
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar"
style="?toolbarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:menu="@menu/report_list"
app:navigationIcon="@drawable/ic_nav_back"
app:subtitle="@string/select_create_report"
app:title="@string/damage_reports" />
</com.google.android.material.appbar.AppBarLayout>
I can locate the toolbar inside my inflated xml like so:
mToolbar = findViewById(R.id.toolbar)
and the menu shows correctly
my problem is that since I haven't inflated the toolbar through onCreateOptionsMenu
I can't use onOptionsItemSelected
to handle events.
so I decided to add straight listeners to the different menu items.
but the thing is that I can't get a reference to them, when I use
mToolbar.findViewById(R.id.search_reports)
it returns null (which frankly I expected) but when I also use
mToolbar.menu.findItem(R.id.search_reports)
I also get null
however when I inspect mToolbar.actionItems[0] I see that the SearchView's string representation shows that its id is
androidx.appcompat.widget.SearchView{c1aeba0 VFE...... ......I. 0,0-0,0 #7f0800fb app:id/search_reports}
and mId from that action item is 2131230971 which translates to 7F0800FB which when searching inside build/generated points to
public static final int search_reports=0x7f0800fb;
but when I inspect R.id.search_reports instead of 2131230971 (which would make the findMenuItem work) I get -1000038
is there something wrong with the setup of my application? or is there a different way to find a specific menu item
edit: as a side note this seems to work
mToolbar.setOnMenuItemClickListener(this::menuItemClicked)
private fun menuItemClicked(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.search_reports -> {
vm.search_stuff()
true
}
else -> false
}
but I would still like to know why findItem does not work
edit 2: for those that may come upon this, it seems that during evaluation and debugging the resource numbers are indeed different, but if you actually place mToolbar.menu.findItem(R.id.search_reports) in your code and run it , it will work, even though it does not work while debugging
Solution
You can set click listener on item like this:
Toolbar toolbar = findViewById(R.id.toolbar);
//remember your menu item id !! mine is R.id.psMenuRefresh
toolbar.getMenu().findItem(R.id.psMenuRefresh).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
Log.i("mytag","helooo");
return false;
}
});
There you go.
Answered By - UrosKekovic
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.