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

来源:互联网 发布:淘宝买裤子怎么选尺码 编辑:程序博客网 时间:2024/06/05 06:53

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个而已。


0 1
原创粉丝点击