单击后如何将新项添加到弹出菜单中

时间:2013-01-17 15:37:09

标签: android onclick menuitem android-menu popupmenu

我有一个按钮:

<Button
        android:id="@+id/bot_button1"
        android:layout_width="120dp"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:textSize="24sp"
        android:text="@string/bot_button1_tx" />  

这是我的主要活动:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    activity = this;

    setContentView(R.layout.activity_main);

    button1 = (Button) findViewById(R.id.bot_button1);
    button1.setOnClickListener(onClickListener);

    Log.d(className, "onCreate");  

private OnClickListener onClickListener = new OnClickListener() {
    @Override
    public void onClick(final View v) {
        switch(v.getId()){
        case R.id.bot_button1:
            showPopupMenu(v, 1);
            break;
        }
    }
};  

private void showPopupMenu(final View v, Integer i){
    PopupMenu popupMenu = new PopupMenu(MainActivity.this, v);
    switch (i) {
    case 1:
        popupMenu.getMenuInflater().inflate(R.menu.menu1, popupMenu.getMenu());
        break;
    }

    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {

            new AlertDialog.Builder(activity).
                setTitle("TITLE").
                setMessage("MESSAGE").
                setAdapter(adapter, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO: user specific action
                        dialog.dismiss();
                    }
              }).create().show();
        return true;
        }
    });
    popupMenu.show();
}  

如果选择(单击)PopupMenu中的项目,如何显示更多项目?理想情况场景:选择后PopupMenu仍然可见,并且所选项目旁边会出现一个新的PopupMenu。或弹出菜单展开以显示子项。

我尝试在onMenuItemClick()上引入第二个PopupMenu,但它只替换了第一个PopupMenu。

1 个答案:

答案 0 :(得分:1)

我使用了一个新的弹出菜单来解决这个问题

public OnMenuItemClickListener listener = new OnMenuItemClickListener() {
    @Override
    public boolean onMenuItemClick(MenuItem item) {

        switch (item.getItemId()) {
        case R.id.menu2_3_3:  
            popupMenu2.getMenuInflater().inflate(R.menu.menu2_3_3, popupMenu2.getMenu());
            popupMenu2.show();
            popupMenu2.setOnMenuItemClickListener(listener2);