android自定义指针,Android实现HID鼠标的指针自定义
寫在前面:本文所提供方法僅供研究學習,不可用于商業用途,轉載請注明出處。
好,正文開始...
首先介紹下藍牙HID設備,指市面上出售的可用于連接PC、Android的可輸入設備,這類設備遵循了hid通信協議,可以用于輸入操作(如按鍵、鼠標移動等),作為一個交互設備存在。
由于hid設備遵循的是其封裝好的通信協議,數據流經過系統封裝好的hid通道來進行傳輸的,因此我們無法直接獲取到其原始輸入數據。但在這次的研究過程中我發現了一種能夠直接獲取到其輸入數據的方法,由于與本文關系不大,這里不再贅述。想了解hid設備原始數據獲取的同學,可以移步我的另一篇博客 。
目的:藍牙hid鼠標在連接到android手機上后會顯示一個系統自帶的鼠標,我們的需求是將該光標進行自定義(調整大小,形狀,圖片資源)。
這里有兩種思路可以選擇:
1.通過替換系統的鼠標圖片資源來實現
2.完全隱藏系統鼠標,由自己的服務來繪制,這時候的自定義操作就相當簡單了
工程最后采用的是第二種方法,不采用第一種思路的原因有很多,android4.0.3源碼之鼠標光標繪制簡略版?這篇博客里詳細描述了android繪制鼠標的過程,簡而言之,系統的鼠標圖片是在資源文件打包了,并且在框架層framework中寫死,android sdk沒有提供任何開放的API來修改系統鼠標(誰會沒事做這個呢?)。當然想替換也不是沒辦法,可以編譯源碼,簡單點的做法是解包framework-res.apk后替換其中的cursor.png圖片后再打包,重啟手機生效。這些方法都顯得非常繁瑣,而且修改一次就得編譯一次或是重啟一次,不能進行動態的實時修改,所以第一種思路pass了。
說了這么多,下面是具體的解決方案:
我們需要自定義鼠標,但又不影響其原有的操作,比如說我們移動鼠標進行點擊,這個不能沒有把,也就是說除了替換鼠標之外,其他功能都必須進行保留。比如點擊,拖動,因此自己畫的鼠標位置需要跟原生鼠標位置保持一致。
第一步: 用透明圖片替換framework-res.apk中的鼠標圖片資源,這里不同手機的位置可能不一樣,但名稱都類似于cursor_arrow.png,全部替換后打包,重啟手機。此時連接hid設備后屏幕不再顯示鼠標(因為是透明的嘛)。
第二步:現在我們隱藏了系統自帶的鼠標,我們需要自己繪制鼠標,并且位置和原來的一致(實現點擊、拖動),繪制鼠標需要我們知道這個原生鼠標(現在已透明了)的位置,怎么獲取呢?各種翻閱sdk文檔后,終于讓我找到了這樣一個方法:
/**
* Implement this method to handle hover events.
*
* This method is called whenever a pointer is hovering into, over, or out of the
* bounds of a view and the view is not currently being touched.
* Hover events are represented as pointer events with action
* {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
* or {@link MotionEvent#ACTION_HOVER_EXIT}.
*
*
*
The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}* when the pointer enters the bounds of the view.
*
The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}* when the pointer has already entered the bounds of the view and has moved.
*
The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}* when the pointer has exited the bounds of the view or when the pointer is
* about to go down due to a button click, tap, or similar user action that
* causes the view to be touched.
*
*
* The view should implement this method to return true to indicate that it is
* handling the hover event, such as by changing its drawable state.
*
* The default implementation calls {@link #setHovered} to update the hovered state
* of the view when a hover enter or hover exit event is received, if the view
* is enabled and is clickable. The default implementation also sends hover
* accessibility events.
*
*
* @param event The motion event that describes the hover.
* @return True if the view handled the hover event.
*
* @see #isHovered
* @see #setHovered
* @see #onHoverChanged
*/
public boolean onHoverEvent(MotionEvent event);
onHoverEvent可以檢測鼠標或者軌跡球在view上移動時,相對于view的坐標位置,問題是只有鼠標在這個view中間移動的時候,才能捕捉得到。
我們需要的鼠標在整個屏幕上的位置,于是,用類似與
未完待續
總結
以上是生活随笔為你收集整理的android自定义指针,Android实现HID鼠标的指针自定义的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为数通HCIE很好考吗?
- 下一篇: 光盘版的DOS启动盘