android按鍵複用

來源:互聯網
上載者:User

標籤:android   style   blog   color   os   io   使用   div   cti   

  最近做android電視系統定製,上面安排我做一個按鍵板按鍵複用的功能:當電視的OSD菜單顯示出來時按鍵板上的 ch+/ch- 複用為方向鍵上/下,vol+/vol- 複用為方向鍵 右/左。  OSD 菜單是使用一個Fragment實現,所以選擇在 OSD 菜單顯示(onResume)觸發按鍵複用功能,在 OSD 菜單消失(onStop)時取消按鍵複用功能。實現的思路是合理的了,我們知道應用程式處理按鍵事件 KeyEvnet 通常是通過事件的keyCode值決定程式要做什麼事,所以只需在處理按鍵函數 onKey,onKeyUp,onKeyDown 等處理按鍵事件前修改事件的keyCode值就可以實現按鍵的複用了,具體到這裡就是把 KEYCODE_CHANNEL_UP/KEYCODE_CHANNEL_DOWN 改為 KEYCODE_DPAD_UP/KEYCODE_DPAD_DOWN 同樣的把 KEYCODE_VOLUME_UP/KEYCODE_VOLUME_DOWN 改為 KEYCODE_DPAD_RIGHT/KEYCODE_DPAD_LEFT。 要在上面提到的函數前修改索引值就需要用到 dispatchKeyEvent(KeyEvent event) 了,官方對該方法的解釋是在按鍵事件被分發到視窗前將其攔截。好了閑話少說代碼如下:  

 1 public boolean dispatchKeyEvent(KeyEvent event) { 2         long downTime= event.getDownTime(); 3         long eventTime = event.getEventTime(); 4         int  action = event.getAction(); 5         int  code = event.getKeyCode(); 6         int repeat = event.getRepeatCount(); 7         int metaState = event.getMetaState(); 8         switch (code) { 9         case KeyEvent.KEYCODE_CHANNEL_UP:10                 event = new KeyEvent(downTime, eventTime, action, KeyEvent.KEYCODE_DPAD_UP, repeat, metaState);11             break;12         case KeyEvent.KEYCODE_CHANNEL_DOWN:13             event = new KeyEvent(downTime, eventTime, action, KeyEvent.KEYCODE_DPAD_DOWN, repeat, metaState);14             break;15         case KeyEvent.KEYCODE_VOLUME_UP:16             event = new KeyEvent(downTime, eventTime, action, KeyEvent.KEYCODE_DPAD_RIGHT, repeat, metaState);17             break;18         case KeyEvent.KEYCODE_VOLUME_DOWN:19             event = new KeyEvent(downTime, eventTime, action, KeyEvent.KEYCODE_DPAD_LEFT, repeat, metaState);20             break;21         }22 23         return super.dispatchKeyEvent(event);24     }

 

 

android按鍵複用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.