Android中RecyclerView的使用(焦点控制)

1、使用GridLayoutManager焦点乱跳的问题解决方法:

	首先贴代码,后面解释 
@Override
    public View onInterceptFocusSearch(View focused, int direction) {
        Log.i(TAG,"onInterceptFocusSearch , focused = "+focused +" direction = "+direction);
        int span = getSpanCount();
        int count = getItemCount();
        int fromPos = getPosition(focused);
        switch (direction) {
            case View.FOCUS_UP:
                fromPos = (fromPos - span);
                break;
            case View.FOCUS_DOWN:
                fromPos = (fromPos + span);
                break;
            case View.FOCUS_RIGHT:
                fromPos++;
                break;
            case View.FOCUS_LEFT:
                fromPos--;
                break;
        }

        Log.i(TAG, "onInterceptFocusSearch , fromPos = "+fromPos + " count = " + count+" span = "+span);
        if(fromPos < 0) {
            return focused;
        } else if(fromPos >= count) {
            return focused;
        } else {
            return findViewByPosition(fromPos);
//            return getChildAt(fromPos);
        }
onInterceptFocusSearch()方法是LayoutManager中用来控制每个item焦点的移动的,传入的参数(View focused, int direction),focused表示当前已经获取焦点的view,direction表示这个当前获取焦点的view的按键操作(如上下左右),返回的对象是类型为View的每个item。总结就是onInterceptFocusSearch(View focused, int direction)方法返回对focused这个View做值为direction的按键操作时下一个获取焦点的View。
特别注意:根据每个item的position(或者说是index)来确定该item的View时,有两种方法,findViewByPosition()和getChildAt(),推荐使用findViewByPosition()。使用getChildAt()会出现一个问题,例如需要的是getChildAt(40),这个40是整个数据中的第40个,但是返回的View却是你RecyclerView视图中的第40个,这就会造成当RecyclerView超出视图,例如固定了RecyclerView的高,第40个数据的item不在视图内,当你使用getChildAt(40)返回的只是你视图可见范围内的第40个而已。

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值