2014-04-05 87 views
0

我希望能夠使用密鑰(即數字1-4)從PopupMenu中選擇一個選項。我正在編寫應用程序的設備具有內置的數字小鍵盤,可以隨時訪問(不使用軟鍵盤)。當PopupMenu可見時檢測密碼

的目標是用戶能夠按一個數字/鍵和菜單將顯示,這是工作,這裏(這是我的活動):

@Override 
public boolean onKeyUp(int keyCode, KeyEvent event){ 
    Log.d("onKeyUp", KeyEvent.keyCodeToString(keyCode)); 
    if (event.getKeyCode() == KeyEvent.KEYCODE_5) { 
     showPopupMenu((Button) findViewById(R.id.btnMenu)); 
    } 
    return true; 
} 

我想可以使用鍵盤從菜單中選擇其中一個選項,但是當菜單可見時,只要按下鍵,onKeyUp事件就不會被觸發。

這裏的菜單代碼:

public void showPopupMenu(View v){ 
    PopupMenu popupMenu = new PopupMenu(this, v); 
    final MenuInflater menuInflator = popupMenu.getMenuInflater(); 

    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { 
     @Override 
     public boolean onMenuItemClick(MenuItem menuItem) { 
      //Do something 
      return true; 
     } 
    }); 

    menuInflator.inflate(R.menu.current_screen_menu, popupMenu.getMenu()); 
    popupMenu.show(); 
} 

這是採用Android 4.1(API 16)。謝謝你的幫助!很高興在需要的地方提供更多代碼。

+0

你能找到一個方法來做到這一點?我正面臨類似的問題! –

+0

嘿,抱歉不能說我能夠得到這個工作。我最終通過使用一個簡單而簡單的'Dialog'來解決它,你可以找到http://developer.android.com/guide/topics/ui/dialogs.html – djston

回答

0

你需要設置的KeyEvent聽衆在popupwindow對象這樣

public void showPopupMenu(View v){ 
    PopupMenu popupMenu = new PopupMenu(this, v); 
    final MenuInflater menuInflator = popupMenu.getMenuInflater(); 

    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { 
     @Override 
     public boolean onMenuItemClick(MenuItem menuItem) { 
      //Do something 
      return true; 
     } 
    }); 

    menuInflator.inflate(R.menu.current_screen_menu, popupMenu.getMenu()); 
    popupMenu.show(); 

    // You have to implement following listner 
    popupMenu.getContentView().setOnKeyListener(new View.OnKeyListener() {   
     @Override 
     public boolean onKey(View v, int keyCode, KeyEvent event) { 
      if (keyCode == KeyEvent.KEYCODE_MENU && 
        event.getRepeatCount() == 0 && 
        event.getAction() == KeyEvent.ACTION_DOWN) { 
       // ... payload action here. e.g. popupMenu.dismiss(); 
       return true; 
      }     
      return false; 
     } 
    }); 
}