onCreateOptionsMenu 总是显示为带有我以编程方式创建的菜单的操作
onCreateOptionsMenu showing alwasy as action with a menu that i have created programatically
下面是我如何以编程方式创建菜单
@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)));
}
下面是我在 SetUpClass 中的 menuInitializer 方法
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;
}
}
如何使以编程方式创建的菜单始终显示为操作,就像使用下面的 xml 菜单时一样
app:showAsAction="always"
使用MenuItem.SHOW_AS_ACTION_ALWAYS
将菜单项设置为始终可见
@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);
}
下面是我如何以编程方式创建菜单
@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)));
}
下面是我在 SetUpClass 中的 menuInitializer 方法
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;
}
}
如何使以编程方式创建的菜单始终显示为操作,就像使用下面的 xml 菜单时一样
app:showAsAction="always"
使用MenuItem.SHOW_AS_ACTION_ALWAYS
将菜单项设置为始终可见
@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);
}