android – 获得最后焦点的孩子

我发现当使用d-pad或轨迹球在我的应用程序中导航时如果向右移动并且列表视图失去焦点,当列表视图重新获得焦点时,不同的孩子将获得焦点而不是最后一个焦点.我尝试使用onFocusChange(…)来保存哪个孩子有焦点,但看起来直到焦点丢失后才调用它,所以我永远无法抓住哪个孩子最后有焦点.有没有办法抓住谁有焦点,所以我可以在列表视图再次抓住焦点后,在子节点上调用requestFocus()?

不幸的是我不能使用处理程序,因为这不是一个很常用的功能,我不想牺牲较小功能的性能.

这是我没有工作的代码(不管是什么,focusedView总是为null):

mainListView.setOnFocusChangeListener(new OnFocusChangeListener() {

        public void onFocusChange(View v, boolean hasFocus) {
            if(focusedView == null ) { Log.i("focus", "focusedView == null"); }
            if(hasFocus && focusedView != null) {
                Log.i("focus", "Focus has been Recieved.............");
                focusedView.requestFocus();
            } else {
                // Focus has been lost so save the id of what the user had selected
                Log.i("focus", "Focus has been Lost.............");
                focusedView = mainListView.findFocus();
            }
        }
    });

谢谢!

最佳答案 我认为你有自己的答案,因为焦点监听器在失去焦点后被调用,因此没有孩子会聚焦,因此.findFocus()将返回null.

我最好的办法是扩展ListView类,并覆盖onFocusChanged方法.基本上做你正在做的事情,但是当gainFocus为真时在其中做.

@Override
protected void onFocusChanged (boolean gainFocus, 
     int direction, Rect previouslyFocusedRect) {
     if(gainFocus)
         focusedView = mainListView.findFocus();

}

This one

点赞