2017-06-11 6 views
0

に発射ません。DispatchKeyEventは、私は私がこれを書いたように、のCustomViewで物理的なキーイベントをインターセプトする必要があります私のビュー

どうすればいいですか?

注:アクティビティで同じメソッドをオーバーライドしても動作しますが、私はCustomViewで実行する必要があります。

+0

キーイベントがアクティビティによって処理されたため、ビューにパスできなかったようです。 –

+0

あなたのカスタムビューにフォーカスが当たった後、KeyEventはアクティビティからCustomViewに渡されます。 –

答えて

1

customViewFocusedFocusableInTouchMode = trueになると、KeyEventにキャッチすることができます。 DispatchEventソースコードから、我々は、この見ることができます。そのため、customView必見のに注目されて

@Override 
public boolean dispatchKeyEvent(KeyEvent event) { 

    if ((mPrivateFlags & (PFLAG_FOCUSED | PFLAG_HAS_BOUNDS)) 
      == (PFLAG_FOCUSED | PFLAG_HAS_BOUNDS)) { 
     // If this ViewGroup is focused and its size has been set(has border),pass the KeyEvent to the view 

     if (super.dispatchKeyEvent(event)) { 
      return true; 
     } 
    } else if (mFocused != null && (mFocused.mPrivateFlags & PFLAG_HAS_BOUNDS) 
      == PFLAG_HAS_BOUNDS) { 
     //If this ViewGroup has a focused child,and the child has a size 
     if (mFocused.dispatchKeyEvent(event)) { 
      return true; 
      // We can see that only the child is focused it can be catch the key event 
     } 
    } 

    if (mInputEventConsistencyVerifier != null) { 
     mInputEventConsistencyVerifier.onUnhandledEvent(event, 1); 
    } 
    return false; 
} 

KeyEvent

をキャッチすることができ、私はあなたのcustomViewにこのコードを追加し、この問題を解決:

public GameView(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) 
{ 
    //Set whether this view can receive the focus 
    this.Focusable = true; 

    //When a view is focusable, it may not want to take focus when in touch mode. 
    //For example, a button would like focus when the user is navigating via a D-pad 
    //so that the user can click on it, but once the user starts touching the screen, 
    //the button shouldn't take focus 
    this.FocusableInTouchMode = true; 
} 

//Returns whether this View is able to take focus 
public override bool IsFocused => true; 
+0

OK!できます!今、私はキーコードを持っていますが、私が押した正しい鍵盤をどうやって得るのですか?スペイン語の鍵「ñ」を押すと、「Keycode.AltLeft」が得られます。実際の鍵を取得する方法はありますか?私はキーマップを気にしていますか? – SuperJMN

+0

私はこれをよりよく説明するためにこの別の質問を作成しました:https://stackoverflow.com/questions/44552029/getting-proper-text-input-from-physical-keyboard-in-android – SuperJMN

関連する問題