I know this question has been asked and but I am unable to solve my problem after looking at those answer. I have an Activity with a Fragment.
In fragment, I have added the toolbar and I want to handle toolbar menu item click events from the fragments.
In menu, I have added a single share button. I am getting the click event callback for the Up navigation (arrow home button) but I am not getting click event callback for the share button in my fragment.
Can some points me at what I am doing wrong here.
menu.xml
<menu 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"
tools:context="com.rahul.haridasasampada.details.DescriptionActivity">
<item
android:id="#+id/action_share"
android:title="Share"
android:orderInCategory="100"
app:showAsAction="always"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider"/>
</menu>
I have added toolbar to the fragment layout.
My Activity's code -
public class DescriptionActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_description);
if (savedInstanceState == null) {
Article articleExtra = (Article) getIntent().getParcelableExtra(DescriptionFragment.ARGS_EXTRA);
DescriptionFragment descriptionFragment = DescriptionFragment.newInstance(articleExtra);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, descriptionFragment)
.commit();
}
}
#Override
protected void onResume() {
super.onResume();
getSupportActionBar().setTitle(R.string.app_name_in_kannada);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_description, menu);
Log.d("debug", "activity : onCreateOptionsMenu");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
Log.d("debug","activity: action home has clicked");
onBackPressed();
return false;
case R.id.action_share:
Log.d("debug","activity: action share has clicked");
return false;
}
return super.onOptionsItemSelected(item);
}
}
My Fragments code -
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// some code
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ActionBarActivity actionBarActivity = (ActionBarActivity) getActivity();
Toolbar toolbar = (Toolbar) getView().findViewById(R.id.toolbar_actionbar);
actionBarActivity.setSupportActionBar(toolbar);
toolbar.setOnMenuItemClickListener(this);
toolbar.inflateMenu(R.menu.menu_description);
}
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_share:
if (menuItem.getItemId() == R.id.action_share)
Log.d("debug","action share has clicked");
return true;
}
return false;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
Log.d("debug", "fragment : onCreateOptionsMenu");
MenuItem shareMenuItem = menu.findItem(R.id.action_share);
mShareActionProvider =(ShareActionProvider)MenuItemCompat.getActionProvider(shareMenuItem);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
Log.d("debug","fragment : action home has clicked");
return true;
case R.id.action_share:
Log.d("debug","fragment: action share has clicked");
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View detailFragmentView = inflater.inflate(R.layout.fragment_description, null);
return detailFragmentView;
}
From Android Docs, for Fragment:
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater)
Initialize the contents of the Activity's standard options menu. You should place your menu items in to menu. For this method to be called, you must have first called setHasOptionsMenu(boolean).
so you want to control actionbar menu in Fragment, then you have to call setHasOptionsMenu method better in Fragment's onCreate(...):
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
also important is that you should not use inflateMenu and onCreateOptionsMenu both together for same ToolBar, inflateMenu is for standalone without setting ToolBar as ActionBar.
Suggestion:
keep one ToolBar in Activity as ActionBar for your App, and another ToolBar standalone inside Fragment.
Hope this help!
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class MyFragment extends Fragment implements Toolbar.OnMenuItemClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list, container, false);
Toolbar toolbar= (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.inflateMenu(R.menu.menu_main);
toolbar.setOnMenuItemClickListener(this);
return rootView;
}
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_menu:
//do sth here
return true;
}
return false;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.training1_fragment, container,
false);
setHasOptionMenu(true);
return v;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save :
{
//Write here what to do you on click
return true;
}
}
return super.onOptionsItemSelected(item);
}
You should getPointer toolbar from your activity class and inflate menu in fragment class.
You can look this ex:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
activity = ((DescriptionActivity ) getActivity());
Toolbar tollbar=getView.findViewById(R.id.your_toolbar);
activity.setSupportActionBar(toolbar);
activity.toolbar.inflateMenu(R.menu.menu_search);
activity.toolbar.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_search:
break;
}
return false;
}
Please refer this for click of the Fragment optionMenu click link.
Related
I'm having a ToolBar made as ActionBar in a Fragment. I'm able to add ActionBar menu items but I'm not able to receive click response when I click on any ActionBar menu item.
I have read a lot of similar questions, I tried all but I'm still facing issue, so asked a question here.
The Fragment
public class DetailFragment extends Fragment {
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
setHasOptionsMenu(true);
return inflater.inflate(R.layout.project_detail, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mToolBar = (Toolbar)view.findViewById(R.id.tb_toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(mToolBar);
mToolBar.setTitle(R.string.project_details);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.project_detail_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.options:
// do something
break;
}
return true;
}
In my case in code above, onOptionsItemSelected is not even getting called.
Any pointers why ?
The Activity where I'm inflating this Fragment -
public class TestJust extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_just);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, new ProjectDetailFragment());
ft.commit();
}
}
project_detail_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/options"
android:title="options"
android:icon="#android:drawable/ic_menu_more"
app:showAsAction="always"/>
</menu>
Most probably your problem is that you're always returning true from the activity's onOptionsItemSelected method.
When you return true, you consume the click event inside the method in the activity, that's why the click event never reaches the onOptionsItemSelected method inside your fragment.
Try this
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear()
inflater.inflate(R.menu.project_detail_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.options:
// do something
return true;
default:
return super.onOptionsItemSelected(item);
}
Solution:
You are calling setHasOptionsMenu(true); in onCreateView()
Please call that method in onCreate()
Like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
Calling this method in onCreate() ensures that the menu must participate in Fragment.
Then,
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_menu_items, menu);
}
Finally,
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.options:
// do something
break;
}
return super.onOptionsItemSelected(item);
It should work now.
initialize option in onCreateOptionMenu then check it. you only inflate menu, use without initialize option, first initialize then use it.
like: MenuItem item = menu.findItem(R.id.option);
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
MenuItem item = menu.findItem(R.id.option);
}
switch (item.getItemId()) {
case R.id.options:
// do something
return true;//<- Here you need to return true because breaking compile from this line returns default false;
default:
return super.onOptionsItemSelected(item);
}
Basically my project have to have different toolbars, one for each fragment switched by the bottom navigation bar.
The fragment toolbars items are clickable, when I long press, shows the title item etc, but they don't perform the action. For example, When I set to show a toast when click on that item, he'll not perform. Any Suggestion? Thanks.
public class FeedFragment extends Fragment {
public static final String TAG = "Tag Free";
DialogFragment mDialog;
FloatingActionButton fab;
RevealFrameLayout reveal;
FrameLayout frame;
private ConstraintLayout layoutDialog;
boolean isOpen = false;
public FeedFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_feed, container, false);
/** Toolbar **/
Toolbar myToolbar = (Toolbar) view.findViewById(R.id.my_toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(myToolbar);
ActionBar ab = ((AppCompatActivity) getActivity()).getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(false);
// navigation bottom
fab = getActivity().findViewById(R.id.fab_button);
fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_pencil_black_24dp));
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentTransaction ft = getFragmentManager().beginTransaction().setCustomAnimations(R.anim.hold, R.anim.slide_down);
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
DialogFragment dialogFragment = new PostDialog();
dialogFragment.show(ft, "dialog");
dialogFragment.setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogFragmentTheme);
}
});
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.appbar_feed, menu);super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_personProfile:
Toast.makeText(getActivity(),"not responding",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), MyUserProfileActivity.class);
startActivity(intent);
return true;
case R.id.action_settings:
Toast.makeText(getActivity(),"not responding",Toast.LENGTH_SHORT).show();
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
}
You are not chaining to the superclass in the activity methods.
Refactor your code as below :
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.appbar_feed, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_personProfile:
Toast.makeText(getActivity(),"not responding",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), MyUserProfileActivity.class);
startActivity(intent);
break;
case R.id.action_settings:
Toast.makeText(getActivity(),"not responding",Toast.LENGTH_SHORT).show();
break;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
break;
}
return super.onOptionsItemSelected(item);
}
Hope now your code will work fine.
I have created a fragment with action bar menu, that menu was shown but not working when its clicked.
Here is My Fragment:
public class ComposeFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_compose, container, false);
userName = (TextView) view.findViewById(R.id.user_name);
subjectSpinner = (Spinner) view.findViewById(R.id.subject_spinner);
sendButton = (Button) view.findViewById(R.id.send_btn);
messageEditText = (EditText) view.findViewById(R.id.message);
userName.setText(Ezcation.getInstance().userName);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.compose_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.e("Menu","Before Switch");
switch (item.getItemId()){
case R.id.sent:
Log.e("Menu","Sent");
if (messageEditText.getText().toString().equals("")){
messageEditText.setError("Please Enter your Message");
}else {
sendMessage(messageEditText.getText().toString());
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.messageActivity = (MessageActivity) context;
SpannableString s = new SpannableString("Compose Message");
s.setSpan(new TypefaceSpan(messageActivity, "Miller-Text.ttf"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
messageActivity.setTitle(s);
}
}
When menu was clicked even Log.e("Menu","Before Switch"); not working.
My Menu xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/sent"
android:title="Sent"
android:orderInCategory="10"
android:icon="#drawable/sent"
app:showAsAction="ifRoom" />
</menu>
For Future visiters you should use this in Activity class:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
To work properly hardcoding false isnt the right way
add this in your Activity.
#Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);;
}
The super call is missing inside onCreateOptionsMenu
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.compose_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
I am working on a navigation drawer in which i am using multiple fragment .In one of the fragment i have to use menu item for some action .Now i can inflate menu item on action bar on that fragment but action is not performing .
public class Location extends Fragment implements View.OnClickListener {
GoogleMap googleMap;
Fragment fragment;
Button arrived_mbtn;
TextView current_mtv,request_mtv;
LinearLayout btn_mlayout,journey_mlayout;
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_location, container, false);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("you are in oncreate", "dfsdfsd");
setHasOptionsMenu(true);
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
try {
if (fragment != null) {
fragment = getFragmentManager().findFragmentById(R.id.map);
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
} catch (Exception e) {
e.printStackTrace();
}
Thread.interrupted();
super.onPause();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
getActivity().getMenuInflater().inflate(R.menu.menu_payment_card_detail,menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.action_settings:
Toast.makeText(getActivity(),"hello",Toast.LENGTH_SHORT);
return true;
}
return super.onOptionsItemSelected(item);
}
}
by this code an item is inflate on action bar but on click it did,t show any thing .
Change like this. You have not called show() on toast.
case R.id.action_settings:
Toast.makeText(getActivity(),"hello",Toast.LENGTH_SHORT).show();
Change your onCreateOptionsMenu method as below.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_payment_card_detail,menu);
}
And whatever id you have applied to your menu item, use that in the condition to check whether that menu item is clicked or not.
in your code:
Move the setHasOptionsMenu(true) in the onCreateView() method;
Use inflater.inflate(R.menu.menu_payment_card_detail,menu); in the
onCreateOptionsMenu method.
Something like this:
#Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_payment_card_detail,menu);
super.onCreateOptionsMenu(menu, inflater);
}
Add the show() method to your Toast Toast.makeText(getActivity(),"hello",Toast.LENGTH_SHORT).show();
In fragment:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set setHasOptionsMenu
setHasOptionsMenu(true);
}
Check the parent activity doesn't eat the item selected, i.e. make sure if the parent activity implements onOptionsItemSelected() that it returns false for your fragment's items.
I have an ActionBarActivity and one Fragment. The Activity has no menu inflated, while the Fragment has a menu with two buttons. Fragment menu is visible, but the buttons don't react at all when tapped. At debugging I can see that both onCreateOptionsMenu() for Fragment and Activity get called, but when tapping buttons no onOptionsItemSelected() gets called, neither from Activity nor from Fragment.
Activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
Fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainActivity = (NavigationActivity)getActivity();
setHasOptionsMenu(true);
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState){
return (ScrollView) inflater.inflate(R.layout.tutoring_detail, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.query_details_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.accept_query:
respondToQuery(true);
return true;
case R.id.decline_query:
respondToQuery(false);
return true;
default:
break;
}
return false;
}
Menu to be displayed in Fragment
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
<item
android:id="#+id/accept_query"
android:orderInCategory="100"
app:showAsAction="always"
android:checkable="true"
style="?android:attr/borderlessButtonStyle"
app:actionViewClass="android.widget.ImageButton"/>
<item
android:id="#+id/decline_query"
android:orderInCategory="101"
app:showAsAction="always"
android:checkable="true"
style="?android:attr/borderlessButtonStyle"
app:actionViewClass="android.widget.ImageButton"/>
</menu>
In the Activity class,
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
return false;
}
In the Fragment,
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(getActivity(), "called " + item.getItemId(), Toast.LENGTH_SHORT).show();
return super.onOptionsItemSelected(item);
}
You must use super.onOptionsItemSelected(item) in the parent activity's onOptionsItemSelected(...) method.
From Activity | Android Developers:
Derived classes should call through to the base class for it to perform the default menu handling.
Try moving setHasOptionsMenu(true) inside of the onCreateView() method in your Fragment instead of onCreate().
I had a similar issue after making special layout for my action button (I made an Image Button and needed to pad it and change some other things so I had to use layout for it).
Then onOptionsItemSelected lost connection with this imageButton so I just use clickListener for it inside onCreateOptionsMenu. It might not be the best practice, maybe there is a better solution, but this is what solve my problem.
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.picker_list_menu, menu);
MenuItem itemDone = menu.findItem(R.id.menu_done);
MenuItemCompat.setActionView(itemDone, R.layout.menu_layout_done);
menuDoneIB = (ImageButton) MenuItemCompat.getActionView(itemDone);
itemDone.getActionView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//your code..
}
});
}
Try using oncreateview
public static class ExampleFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.example_fragment, container, false);
}
}
If you have dynamically changed menu item, for instance, a badge menu (https://stackoverflow.com/a/16648170/2914140 or https://stackoverflow.com/a/26017587/2914140), you should initialize the item in onCreateOptionsMenu and re-set setOnClickListeners after every change of the item.
In my case:
private MenuItem menuItem;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_catalog, menu);
menuItem = menu.findItem(R.id.action_badge);
writeBadge(0);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_badge) {
// Your code.
return true;
}
return super.onOptionsItemSelected(item);
}
private void writeBadge(int count) {
MenuItemCompat.setActionView(menuItem, R.layout.item_badge);
RelativeLayout layout = (RelativeLayout) MenuItemCompat.getActionView(menuItem);
// A TextView with number.
TextView tv = (TextView) layout.findViewById(R.id.badge);
if (count == 0) {
tv.setVisibility(View.INVISIBLE);
} else {
tv.setVisibility(View.VISIBLE);
tv.setText(String.valueOf(count));
}
// An icon, it also must be clicked.
ImageView imageView = (ImageView) layout.findViewById(R.id.image);
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
onOptionsItemSelected(menuItem);
}
};
menuItem.getActionView().setOnClickListener(onClickListener);
imageView.setOnClickListener(onClickListener);
}
I am passing the click event to fragment from the activity. This worked for me.
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
return getSupportFragmentManager().getFragments().get(getSupportFragmentManager().getFragments().size() - 1)
.onOptionsItemSelected(item);
}