我使用的Android设备没有任何触摸屏。它只有一个触摸板,可以生成KEYCODE_DPAD_UP,KEYCODE_DPAD_DOWN等。但是,我不确定我的Xamarin应用程序是否响应这些事件。是否有任何设置可以启用以识别一组控件中的当前选择。
当我进入设备的主屏幕并使用DPad键移动时,我看到当前所选图标周围有一个薄方框。我希望Xamarin应用程序中有类似的设置来打开这种行为。问候。
答案 0 :(得分:2)
You can simply use CurrentFocus
of the activity to get the current focused control. But first of all, when control is focused, it will be highlighted, usually we can modify the control's background to a drawable state list resource for example:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/button_pressed" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="@drawable/button_focused" /> <!-- focused -->
<item android:state_hovered="true"
android:drawable="@drawable/button_focused" /> <!-- hovered -->
<item android:drawable="@drawable/button_normal" /> <!-- default -->
</selector>
This visual behavior is for a button to indicate that user has navigated to the control.
When I go the device's home screen and use the DPad keys to move around, I see a thin square around the icon that is currently selected. I am hoping there is a similar setting within Xamarin app to turn on this behavior.
So this thin square can be the designed background for focused state.
I don't know if there is any setting for it, but if you want to do it in code behind to indicate which control is currently focused, as I said at the beginning, you can use CurrentFocus
of the activity. For example:
public override bool DispatchKeyEvent(KeyEvent e)
{
if (e.Action == KeyEventActions.Up)
{
if (e.KeyCode == Keycode.DpadDown || e.KeyCode == Keycode.DpadUp
|| e.KeyCode == Keycode.DpadLeft || e.KeyCode == Keycode.DpadRight)
{
var view = this.CurrentFocus;
view.SetBackgroundDrawable(...);
}
}
return base.DispatchKeyEvent(e);
}
Forget to say, if you want to do it in code behind, don't forget to change the background back to its old state when a new control is focused. Emmm, seems the state list resource is the best choice here.