Get context of PopupMenu like ContextMenu

那年仲夏 提交于 2019-11-26 15:29:57

So I figured out that in order to have some context of which menu icon was clicked, I utilized the setTag() and getTag() methods of the View class and just applied these methods to the ImageView (menu icon).

Re MiDa

You need:

  • A View where to inflate the PopUpMenu (your ImageView)
  • A PopUpMenu saved in res/menu, in this case popup_select_deselect.xml
  • Your own onMenuItemClickListener declared as internal class, in this case onMenuItemClickListener_View

Code:

//TODO initialize rows[]
for (int i = 0; i < rows.lenght; i++){
    //inflate you group_row
    getLayoutInflater().inflate(R.layout.group_row, (ViewGroup)findViewById(R.id.rows_container)); 

   ImageView v_Overflow = (ImageView)findViewById(R.id.Menu);

   //Set onClickListener
   v_Overflow.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    View v_Button = v;
                    PopupMenu pum= new PopupMenu(YourActivity.this, v);

                    //set my own listener giving the View that activates the event onClick (i.e. YOUR ImageView)
                    pum.setOnMenuItemClickListener(new onMenuItemClickListener_View(v) );
                           //inflate your PopUpMenu
                    getMenuInflater().inflate(R.menu.popup_select_deselect, pum.getMenu());
                    pum.show();

                }
            });


    //Update the id of your TextView
    .setId(i); //the i value will be your UNIQUE id for the ImageView

}

The code above is only a static declaration of what your own OnMenuItemClickListener will do.

Pay attention to the given View in the constructor of the following listener. When you create an instance of this listener, the View Id is the same declared in the XML layout. At runtime it will be updated, so when the method onMenuItemClick will be called, the TextView ID is already changed.

Here's the code:

private class onMenuItemClickListener_View implements OnMenuItemClickListener{

    View v_View;

    public onMenuItemClickListener_View(View v){
        v_View=v;
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {

        int i = v_View.getId();

        switch (item.getItemId()) {
            case R.id.popupItemSelectAll:
                Toast.makeText(YourActivity.this, "Popup Select All for View #: " +  rows[i], Toast.LENGTH_SHORT).show();

                //TODO your code to select all
                return true;
            case R.id.popupItemDeselectAll:
                Toast.makeText(YourActivity.this, "Popup Deselect All for View #: " + rows[i], Toast.LENGTH_SHORT).show();

                //TODO your code to deselect all


            return true;
                default:
                    return false;
            }

        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!