Custom ViewGroup focus handling

試著忘記壹切 提交于 2019-12-04 22:35:41

After digging in Android sources I understand how to dispatch focus to ViewGroup's children. For example I have custom ViewGroup with few EditText fields inside. When the user clicks on ViewGroup (outside of each EditText) I want to dispatch focus to one of fields.

To do this we need to set descendantFocusability to FOCUS_AFTER_DESCENDANTS. It means that we can handle focus event before our custom view will try to focus itself:

setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);


Next step is to override onRequestFocusInDescendants method, it will be invoked before custom view's requestFocus if flag FOCUS_AFTER_DESCENDANTS was set. In this method we can request child focus:

@Override
protected boolean onRequestFocusInDescendants(final int dir, final Rect rect) {
    return getChildAt(this.target).requestFocus();
}

One important thing with this method: if we return true here, our custom view will not be requested to focus (only with FOCUS_AFTER_DESCENDANTS).

In such a manner we can change target field to change which child will be focused when ViewGroup is clicked.


For better understanding you can find requestFocus method in ViewGroup in Android sources.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!