【问题标题】:Fill popupmenu without XML file in android在android中填充没有XML文件的弹出菜单
【发布时间】:2012-03-23 06:48:30
【问题描述】:

我有这个代码,这很完美。只有我想在没有 xml 文件(actions.xml)的情况下使这个动态。我该怎么做?

public void showPopup(View v) {
    PopupMenu popup = new PopupMenu(this, v);
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.actions, popup.getMenu());
    popup.show();
}

【问题讨论】:

    标签: android xml menu popupmenu


    【解决方案1】:

    在 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"
    android:theme="@style/AppTheme" />
    

    然后使用getMenu添加新的菜单项如下:

    Button btn1= (Button) findViewById(R.id.btn_test);
    PopupMenu popup = new PopupMenu(yourFormName.this, btn1);  
                        //Inflating the Popup using xml file  
                     popup.getMenu().add("Menu1 Label");
                     popup.getMenu().add("Menu2 Label");
                     popup.getMenuInflater().inflate(R.menu.YourXMLFileName, popup.getMenu());  
    
    
                        //registering popup with OnMenuItemClickListener  
                        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {  
                         public boolean onMenuItemClick(MenuItem item) {  
                           //---your menu item action goes here ....
                          Toast.makeText(DisplayTransactions.this,"You Clicked : " + item.getTitle(),Toast.LENGTH_SHORT).show();  
                          return true;  
                         }  
                        });  
                        popup.show();//showing popup menu  
    

    【讨论】:

      【解决方案2】:

      使用popup.getMenu(),然后使用add的各种重载直接添加项目。

      【讨论】:

      • Nice tnx!:) 你知道如何设置 PopupMenu 的样式吗??
      • 我不知道具体该怎么做,不。你可以看看theserelatedquestions。
      • 如何获取选中值?
      猜你喜欢
      • 1970-01-01
      • 2017-12-23
      • 2013-06-17
      • 2020-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 1970-01-01
      相关资源
      最近更新 更多