listview Popupmenu显示错误值

时间:2014-09-25 20:50:20

标签: android popupmenu click

我试图在点击其弹出菜单时显示列表视图的项目名称但是我遇到了麻烦,因为它总是显示或返回“false”值。任何想法如何解决这个问题?感谢

   public void toast(View v){
        showPopupMenu(v);
    }
    private void showPopupMenu(View v){
        PopupMenu pop = new PopupMenu(CompanyActivity.this, v);
        pop.getMenuInflater().inflate(R.menu.menu,pop.getMenu());

        pop.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if(item.getItemId() == R.id.view){
                    Toast.makeText(getApplicationContext(),item.getItemId(),Toast.LENGTH_SHORT)
                          .show();

                    return true;
                }

                return false;
            }
        });

        pop.show();
    }

已编辑:我希望单击列表视图中的列表项的值,但它会显示正在单击的菜单项。

public void toast(View v){
        showPopupMenu(v);
    }
    private void showPopupMenu(View v){
        PopupMenu pop = new PopupMenu(CompanyActivity.this, v);
        pop.getMenuInflater().inflate(R.menu.menu,pop.getMenu());

        pop.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Toast.makeText(CompanyActivity.this,"text: "+item.getTitle(),Toast.LENGTH_SHORT).show();

                return true;
                }
            });
        pop.show();
    }

1 个答案:

答案 0 :(得分:0)

"名称"您的ListView项目完全取决于您为ListView使用的适配器。请记住,菜单项ID与listview视图id无关,后者与适配器项ID无关。为了让弹出菜单知道单击了哪个项目,您需要使用列表项位置从适配器中查找它。它会像这样工作:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    showPopupMenu(view, position);
}
private void showPopupMenu(View anchor, final int position) {
    PopupMenu popupMenu = new PopupMenu(
            this,
            anchor);
    popupMenu.inflate(R.menu.menu);

    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            // Depending on what type of object backs your adapter, you may have
            // to do something different here.
            String title = String.valueOf(mListView.getAdapter().getItem(position));
            Toast.makeText(MyActivity.this, "text: " + title, Toast.LENGTH_SHORT).show();

            return true;
        }
    });
    popupMenu.show();
}