Below is how i have created my menu programmatically
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.add(0, 0, 0, new SetUpClass().menuInitializer(
Objects.requireNonNull(ContextCompat.getDrawable(requireActivity(),R.drawable.ic_cart)),
getResources().getString(R.string.cart)));
}
Below is my menuInitializer method in SetUpClass
public class SetUpClass {
public CharSequence menuInitializer(Drawable drawable, String title) {
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
SpannableString spannableString = new SpannableString(" " title);
ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BOTTOM);
spannableString.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}
}
How can i make the programmatically created menu to always show as action like when using xml menu like below
app:showAsAction="always"
CodePudding user response:
Use MenuItem.SHOW_AS_ACTION_ALWAYS
to set menu item as always visible
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
MenuItem menuItem = menu.add(0, 0, 0, new SetUpClass().menuInitializer(
Objects.requireNonNull(ContextCompat.getDrawable(requireActivity(),R.drawable.ic_cart)),
getResources().getString(R.string.cart)));
menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}