2014-09-25 99 views
0

我試圖顯示listview的項目名稱,當其popup菜單被點擊,但我有麻煩,因爲它總是顯示或返回「false」值。任何想法如何解決這個問題?感謝listview Popupmenu顯示錯誤值

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(); 
    } 
+0

爲什麼你這樣做「item.getItemId()== R.id.view」? – BlaShadow 2014-09-25 20:58:37

+0

即時消息檢查項目點擊是否等於我的menu.xml中的項目,我做對了嗎? – Jonathan 2014-09-25 21:00:16

+0

如果你創建一個上下文菜單,你可能做錯了什麼,但試着看看這個http://developer.android.com/guide/topics/ui/menus.html#context-menu – BlaShadow 2014-09-25 21:05:33

回答

0

ListView項的「名稱」完全取決於您用於ListView的適配器。請記住,菜單項ID與列表視圖ID無關,該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(); 
}