android 获得焦点(View get focus)

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

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

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

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

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

  mAddButton.setFocusable(true);

  mAddButton.requestFocus();

  mAddButton.setFocusableInTouchMode(true);



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)方法,经测试可以解决问题 
如你知道其他方法,望不吝赐教 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Android 中,焦点移动可以通过以下几种方式实现: 1. 通过代码设置焦点:可以通过调用 View 的 requestFocus() 方法来设置焦点,例如: ``` EditText editText = findViewById(R.id.editText); editText.requestFocus(); ``` 2. 通过 XML 属性设置焦点:可以在 XML 文件中使用 android:focusable 和 android:focusableInTouchMode 属性来设置 View 是否可获得焦点,例如: ``` <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:focusable="true" android:focusableInTouchMode="true" /> ``` 3. 通过监听器处理焦点:可以通过设置 View 的 OnFocusChangeListener 来监听焦点变化事件,例如: ``` editText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { // 处理获取焦点事件 } else { // 处理失去焦点事件 } } }); ``` 4. 通过键盘事件处理焦点:可以在处理键盘事件时,根据当前焦点 View 的 ID 或位置,计算出下一个需要获得焦点View,并调用其 requestFocus() 方法来设置焦点,例如: ``` editText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) { View nextView = v.focusSearch(View.FOCUS_DOWN); if (nextView != null) { nextView.requestFocus(); return true; } } return false; } }); ``` 以上是几种常见的焦点移动方式,可以根据自己的需求选择合适的方式来实现。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值