大家好,又见面了,我是你们的朋友全栈君。
1. 前言
在调试Android
原生Setting
开始中,遇到DialogPreference
中用遥控器操作SeekBar
到100%
时,再按一次右键SeekBar
焦点会跳至确定按钮中去。正常现象应该是停留至SeekBar
尾部。
2. 问题分析
根本原因就是焦点变化了,当SeekBar
为100%
时,再按一次右键让焦点停留再当前位置即可。
进一步分析就是对按键进行处理,当满足条件时,使系统不再处理这个按键。
3. 原生代码片段
在View.java中
/** * Interface definition for a callback to be invoked when a hardware key event is * dispatched to this view. The callback will be invoked before the key event is * given to the view. This is only useful for hardware keyboards; a software input * method has no obligation to trigger this listener. */
public interface OnKeyListener {
/** * Called when a hardware key is dispatched to a view. This allows listeners to * get a chance to respond before the target view. * <p>Key presses in software keyboards will generally NOT trigger this method, * although some may elect to do so in some situations. Do not assume a * software input method has to be key-based; even if it is, it may use key presses * in a different way than you expect, so there is no way to reliably catch soft * input key presses. * * @param v The view the key has been dispatched to. * @param keyCode The code for the physical key that was pressed * @param event The KeyEvent object containing full information about * the event. * @return True if the listener has consumed the event, false otherwise. */
boolean onKey(View v, int keyCode, KeyEvent event);
}
4. onKey返回值说明
由上面的代码可见,对按键监听时,onKey
的返回值不同,代表对按键的不同处理方式。
false: 抛给系统处理 (将事件放行,焦点会移动)
true: 用户自己处理 (将事件拦截,焦点不会移动)
因此,当满足条件时,让onKey
的返回值为true
即可将键值拦截下来由用户自己处理,系统便不再响应这个按键,焦点便不会移动。
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/160607.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...