问题
The Android device I am using does not have any touchscreen. All it has is a touch pad that can generate KEYCODE_DPAD_UP, KEYCODE_DPAD_DOWN, etc. However, I am not sure if my Xamarin app is responding to these events. Is there any setting that one can enable to identify current selection among a group of controls.
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. Regards.
回答1:
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.
来源:https://stackoverflow.com/questions/45471963/how-to-indicate-currently-selected-control-in-xamarin