C# DispatchKeyEvent未在我的视图上触发
我需要在CustomView中截获物理密钥事件,因此我写了以下内容:C# DispatchKeyEvent未在我的视图上触发,c#,android,xamarin,keyboard,xamarin.android,C#,Android,Xamarin,Keyboard,Xamarin.android,我需要在CustomView中截获物理密钥事件,因此我写了以下内容: public class CustomView : View { public override bool DispatchKeyEvent(KeyEvent e) { return base.DispatchKeyEvent(e); } } 我不知道为什么当我按下任何键时从不调用DispatchKeyEvent 我怎样才能让它工作
public class CustomView : View
{
public override bool DispatchKeyEvent(KeyEvent e)
{
return base.DispatchKeyEvent(e);
}
}
我不知道为什么当我按下任何键时从不调用DispatchKeyEvent
我怎样才能让它工作
注意:似乎在活动中重写相同的方法是可行的,但我需要在我的CustomView中执行此操作。一旦您的CustomView被聚焦并且FocusableInTouchMode=true,您就可以捕获KeyEvent。从DispatchEvent源代码中,我们可以看到:
@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;
}
因此,customView必须聚焦于能够捕获KeyEvent
若要解决此问题,请将此代码添加到customView:
关键事件似乎已由活动处理,因此无法传递到视图。您的Customview必须聚焦,然后关键事件才能从活动传递到Customview。确定!它起作用了!现在我有了按键代码,但是我怎么才能得到我按下的正确的键盘字母呢?结果是按西班牙语键ñI得到Keycode.AltLeft。有没有办法拿到真正的钥匙?我的意思是,关注关键地图?我创建了一个单独的问题来更好地解释它:当视图处于活动状态时,您还需要请求焦点
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;