Androidでスタイラスを利用する方法②
2014年03月13日
今回は、スタイラスのボタンの状態・ホバーイベント・入力デバイスの情報を取得する方法を紹介します。
1. ボタンの状態取得
ボタンの状態はMotionEvent.getButtonState()で取得します。
状態はビットで管理されているので、2進数で表示します。
public boolean onTouch(View v, MotionEvent event) { ・ ・ ・ // ボタンの状態取得 int buttonState = event.getButtonState(); log += "ButtonState : " + Integer.toBinaryString(buttonState) + "\n"; m_LogText.setText(log); }
実際に端末上で動作を確認すると、1個目のボタンで2bit目、2個目のボタンで3bit目が1になるのがわかります。
これだけでは、ペンが画面に接している時にしかボタンが使えませんので、ペンがホバー状態になってる時に発生するイベントを追加しましょう。
2. ホバーイベントの追加
タッチイベントと同じように、OnHoverListenerを実装し、レイアウトに対してOnHoverListenerを設定します。
public class MainActivity extends Activity implements OnTouchListener, OnHoverListener
// タッチイベント設定 RelativeLayout layout = (RelativeLayout)this.findViewById(R.id.main_layout); layout.setOnTouchListener(this); layout.setOnHoverListener(this);
ホバーイベントは、タッチイベントと同じく、MotionEventが引数に指定されていますので、画面に出力するメソッド(outputMotionEvent)を作成し、onTouchとonHoverに設定しました。
// タッチイベントの処理 @Override public boolean onTouch(View v, MotionEvent event) { outputMotionEvent(event); return true; } // ホバーイベントの処理 @Override public boolean onHover(View v, MotionEvent event) { outputMotionEvent(event); return true; }
アプリケーションを実行すると、ペン先を画面に接することなく、座標やボタンの情報などが取得できたかと思います。
3. 入力デバイスの情報取得
MotionEventからは、そのイベントを発生させた入力デバイスの情報を取得することができます。
今回は、入力デバイスの名前とディスクリプタを取得し、画面上に表示します。
ディスクリプタは入力デバイスに割り当てられた固定の識別子です。
ディスクリプタを利用することで、入力デバイスに関連付けた設定などを保存することができます。
// ログ出力 public void outputMotionEvent(MotionEvent event) { ・ ・ ・ // 端末情報 log += "--------------------------------------\n"; InputDevice device = event.getDevice(); log += "device name : " + device.getName() + "\n"; log += "device descriptor : " + device.getDescriptor() + "\n"; m_LogText.setText(log); }
タッチとペンで入力デバイスの情報が変わるので、アプリケーションを実行して試してみましょう。
次回は、MotionEventの履歴(getHistorical系)の紹介をします。
サンプルソースはこちらにアップしてありますので、興味のある方は実際に試して頂ければと思います。