前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android View中OnKeyListener的onKey返回值

Android View中OnKeyListener的onKey返回值

作者头像
全栈程序员站长
发布2022-09-13 13:06:41
9640
发布2022-09-13 13:06:41
举报

大家好,又见面了,我是你们的朋友全栈君。

1. 前言

在调试Android原生Setting开始中,遇到DialogPreference中用遥控器操作SeekBar100%时,再按一次右键SeekBar焦点会跳至确定按钮中去。正常现象应该是停留至SeekBar尾部。

2. 问题分析

根本原因就是焦点变化了,当SeekBar100%时,再按一次右键让焦点停留再当前位置即可。 进一步分析就是对按键进行处理,当满足条件时,使系统不再处理这个按键。

3. 原生代码片段

View.java中

代码语言:javascript
复制
    /** * 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的返回值不同,代表对按键的不同处理方式。

代码语言:javascript
复制
false: 抛给系统处理 (将事件放行,焦点会移动)
true:  用户自己处理 (将事件拦截,焦点不会移动)

因此,当满足条件时,让onKey的返回值为true即可将键值拦截下来由用户自己处理,系统便不再响应这个按键,焦点便不会移动。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/160607.html原文链接:https://javaforall.cn

本文参与?腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体同步曝光计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 前言
  • 2. 问题分析
  • 3. 原生代码片段
  • 4. onKey返回值说明
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com