android 获得焦点(View get focus)

来源:互联网 发布:中国地下长城 知乎 编辑:程序博客网 时间:2024/05/07 16:22

button.requestFocus();要得到焦点,理论上是可以的。

  如果不能的话,有两种方法:

  1、制作xml时就把想拥有focus的view放前面——有些情况下用这个难度是挺大的

  2、用requestFocus设置focus。理论上这个是没问题的,但这有前提,就是调用的时机,如果调用的太早了就会被系统的冲掉。

  最后我用了下面三句,实现了获得焦点。

  mAddButton.setFocusable(true);

  mAddButton.requestFocus();

  mAddButton.setFocusableInTouchMode(true);



android 获得焦点(View get focus)

    博客分类: 
  • Android
Android 
android version 1.5 
在SDK帮助文档中有这么一段: 

Java代码  收藏代码
  1. Remember that key events are always delivered to the View currently in focus. They are dispatched starting from the top of the View hierarchy, and then down, until they reach the appropriate destination. If your View (or a child of your View) currently has focus, then you can see the event travel through the [color=green]dispatchKeyEvent()[/color] method. As an alternative to capturing key events through your View, you can also receive all of the events inside your Activity with [color=green]onKeyDown()[/color] and [color=green]onKeyUp()[/color].  


大概的意思是: 键盘事件只会发送到当前获得焦点的View,且这些事件会从上倒下去寻找合适的接受组件,如果你的View或其子组件当前获得焦点,那么你可以通过dispatchKeyEvent()函数来查看事件的详细处理过程,为了方便捕捉时间,android也针对Activity提供了onKeyDown() 和onKeyUp().两个函数来处理所有事件。 

开发过程中,如果在View中处理事件监听函数,那么一定要记得让当前处理的view获得焦点,文档上介绍通过setFocusable(true);函数处理。在实际开发过程中发现,单纯的完成以上操作后,在模拟器上跑程序测试,在第一次按下按键后,程序并没有执行onKeydown(),对这种情况,我做了如下处理: 

使用ViewGroup的requestChildFocus (View child, View focused)方法,经测试可以解决问题 
如你知道其他方法,望不吝赐教