获取Android的菜单从Res/menu以编程方式。

huangapple go评论122阅读模式
英文:

Android Get Menu from Res/menu Programmatically

问题

在Java中:

public Menu getMenuFromResID(@MenuRes int menuRes) {
    PopupMenu popupMenu = new PopupMenu(getContext(), new View(getContext()));
    MenuInflater inflater = popupMenu.getMenuInflater();
    inflater.inflate(menuRes, popupMenu.getMenu());
    return popupMenu.getMenu();
}

请注意,你需要导入相关的类和包以使这些代码正常工作。

英文:

I am creating a custom BottomNavigation using LinearLayout. I want to use Menu as items.

<com.sam.grocerystore.views.XBottomNavigation
    android:id="@+id/customBottomNav"
    android:layout_width="match_parent"
    android:layout_height="55dp"/>

In Java

XBottomNavigation xNav = new XBottomNavigation(this);

xNav.inflateMenu(R.menu.bottom_nav_menu);

In XBottomNavigation

public void inflateMenu(@MenuRes int menuRes){
    Menu menu = getMenuFromResID(menuRes);
}

Can someone help me to create getMenuFromResID funtion;

答案1

得分: 1

我使用 PopupMenu 解决了这个问题。

public void inflateMenu(@MenuRes int menuRes) {
    PopupMenu p = new PopupMenu(getContext(), null);
    menu = p.getMenu();
    new MenuInflater(getContext()).inflate(menuRes, menu);
    for (int i = 0; i < menu.size(); i++) {
        MenuItem item = menu.getItem(i);
        // yourFunctionToCreateItemUI(i, item);
    }
}
英文:

I solved this problem using PopupMenu

public void inflateMenu(@MenuRes int menuRes) {
    PopupMenu p = new PopupMenu(getContext(), null);
    menu = p.getMenu();
    new MenuInflater(getContext()).inflate(menuRes, menu);
    for (int i = 0; i < menu.size(); i++) {
        MenuItem item = menu.getItem(i);
        // yourFunctionToCreateItemUI(i, item);
    }
}

huangapple
  • 本文由 发表于 2020年7月22日 23:28:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63037829.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定