Android TV開發——RecyclerView For TV

小欣兒發表於2018-07-19

原文連結:重寫RecyclerView使其在TV端執行

TV應用中使用原生RecyclerView使用時的侷限性:
例如焦點顯示不全,無法定位到某個position等等

下面總結下在TV端使用使用RecyclerView時踩過的坑

(一) 解決RecyclerView重新整理資料的時候,焦點錯亂問題

下面是google官方給出的解決方案

1. adapter呼叫setHasStableIds(true)方法

2. 重寫getItemId()方法,讓每個view都有各自的id

public abstract class BaseRecyclerAdapter<VH extends BaseRecyclerViewHolder, T> extends RecyclerView.Adapter<BaseRecyclerViewHolder> {

    public LayoutInflater mInflate;

    public List<T> mDataList;

    public BaseRecyclerAdapter(Context context, List<T> dataList)     {
        this.mInflate = LayoutInflater.from(context);
        this.mDataList = dataList;
        setHasStableIds(true);
    }

    public void setDataList(List<T> dataList) {
        this.mDataList = dataList;
    }

    public void addDataList(List<T> dataList) {
        if (dataList != null && dataList.size()>0) {
            this.mDataList.addAll(dataList);
        }
    }

    @Override
    public int getItemCount() {
        return mDataList != null ? mDataList.size() : 0;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    public List<T> getDataList() {
        return mDataList;
    }

    @Override
    public void onBindViewHolder(BaseRecyclerViewHolder holder, int position) {
        onBindBaseViewHolder((VH) holder, position);
    }

    public abstract VH onCreateViewHolder(ViewGroup parent, int viewType);

    protected abstract void onBindBaseViewHolder(VH viewHolder, int position);

    /**
     * @param hasStableIds 有多個observer的話會報錯
     */
    @Override
    public void setHasStableIds(boolean hasStableIds) {
        super.setHasStableIds(hasStableIds);
    }
}

3. RecyclerView的動畫必須去掉

setItemAnimator(null);

(二)解決長按遙控器,讓RecyclerView快速滑動,焦點錯亂問題

1. 由於長按遙控器的時候,RecyclerView找不到findFocusView為null,此時我就把RecyclerView的onKeyUp事件給遮蔽了

2. 通過FocusFind類找到view,並讓view請求焦點;

3.focusFind焦點失敗之後,如果是讓其滑動item的寬度(左後滑動)或者高度(上下滑動),因為有可能滑到下面還有可能有item,否則RecyclerView將不會繼續滑動

 @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (mInterceptLister != null && mInterceptLister.onIntercept(event)) {
            return true;
        }


        boolean result = super.dispatchKeyEvent(event);
        View focusView = this.findFocus();
        if (focusView == null) {
            return result;
        } else {

            int dy = 0;
            int dx = 0;
            if (getChildCount() > 0) {
                View firstView = this.getChildAt(0);
                dy = firstView.getHeight();
                dx = firstView.getWidth();
            }
            if (event.getAction() == KeyEvent.ACTION_UP) {
                return true;
            } else {
                switch (event.getKeyCode()) {
                    case KeyEvent.KEYCODE_DPAD_RIGHT:
                        View rightView = FocusFinder.getInstance().findNextFocus(this, focusView, View.FOCUS_RIGHT);
                        Log.i(TAG, "rightView is null:" + (rightView == null));
                        if (rightView != null) {
                            rightView.requestFocus();
                            return true;
                        } else {
                            this.smoothScrollBy(dx, 0);
                            return true;
                        }
                    case KeyEvent.KEYCODE_DPAD_LEFT:
                        View leftView = FocusFinder.getInstance().findNextFocus(this, focusView, View.FOCUS_LEFT);
                        Log.i(TAG, "leftView is null:" + (leftView == null));
                        if (leftView != null) {
                            leftView.requestFocus();
                            return true;
                        } else {
                            this.smoothScrollBy(-dx, 0);
                            return true;
                        }
                    case KeyEvent.KEYCODE_DPAD_DOWN:
                        View downView = FocusFinder.getInstance().findNextFocus(this, focusView, View.FOCUS_DOWN);
                        Log.i(TAG, " downView is null:" + (downView == null));
                        if (downView != null) {
                            downView.requestFocus();
                            return true;
                        } else {
                            this.smoothScrollBy(0, dy);
                            return true;
                        }
                    case KeyEvent.KEYCODE_DPAD_UP:
                        View upView = FocusFinder.getInstance().findNextFocus(this, focusView, View.FOCUS_UP);
                        Log.i(TAG, "upView is null:" + (upView == null));
                        if (event.getAction() == KeyEvent.ACTION_UP) {
                            return true;
                        } else {
                            if (upView != null) {
                                upView.requestFocus();
                                return true;
                            } else {
                                this.smoothScrollBy(0, -dy);
                                return true;
                            }

                        }
                }

            }

        }
        return result;
    }

(三)解決RecyclerView 定位到某個item不獲取焦點問題

RecyclerView僅僅提供了一個smoothScrollToPosition(int position)方法,而且該方法,能滑到指定的position位置,但是該position處的item並沒有獲取焦點。

想起在使用LeanBack中的RecyclerView時,你會發現它提供了專門定位到某個position,並獲取焦點的方法。但是然後沉下心把原始碼給看了,終於明白了其中的原理,原來它在定位到指定位置的item後,找到目標的item,並讓其主動請求焦點。完美解決

(1) RecyclerView的smoothScrollToPosition方法,最終執行的是LayoutManger的smoothScrollToPosition方法。下面是RecyclerView的
smoothScrollToPosition的原始碼

  public void smoothScrollToPosition(int position) {
        if (mLayoutFrozen) {
            return;
        }
        if (mLayout == null) {
            Log.e(TAG, "Cannot smooth scroll without a LayoutManager set. " +
                    "Call setLayoutManager with a non-null argument.");
            return;
        }
        mLayout.smoothScrollToPosition(this, mState, position);
    }

(2) RecyclerView彈性滑動是通過SmoothScroller來實現的,SmoothScroller中有onStart和onStop的回撥,大膽猜測一下,onStop肯定是滑動結束的回撥,於是找到targetView,並讓其請求焦點,問題得以解決

/**
 * Created by liuyu on 17/2/8.
 * fix issue: RecyclerView 進行item定位的時候,item沒有獲取焦點
 */
public class TvGridLayoutManager extends GridLayoutManager {
    public TvGridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public TvGridLayoutManager(Context context, int spanCount) {
        super(context, spanCount);
    }

    public TvGridLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout) {
        super(context, spanCount, orientation, reverseLayout);
    }


    /**
     * Base class which scrolls to selected view in onStop().
     */
    abstract class GridLinearSmoothScroller extends LinearSmoothScroller {


        public GridLinearSmoothScroller(Context context) {
            super(context);
        }

        /**
         * 滑動完成後,讓該targetPosition 處的item獲取焦點
         */
        @Override
        protected void onStop() {
            super.onStop();
            View targetView = findViewByPosition(getTargetPosition());

            if (targetView != null) {
                targetView.requestFocus();
            }
            super.onStop();
        }

    }

    /**
     * RecyclerView的smoothScrollToPosition方法最終會執行smoothScrollToPosition
     * @param recyclerView
     * @param state
     * @param position
     */
    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
                                       int position) {
        GridLinearSmoothScroller linearSmoothScroller =
                new GridLinearSmoothScroller(recyclerView.getContext()) {
                    @Override
                    public PointF computeScrollVectorForPosition(int targetPosition) {
                        return computeVectorForPosition(targetPosition);
                    }
                };
        linearSmoothScroller.setTargetPosition(position);
        startSmoothScroll(linearSmoothScroller);
    }

    public PointF computeVectorForPosition(int targetPosition) {
        return super.computeScrollVectorForPosition(targetPosition);
    }
}

為了方便大家我把程式碼上傳到了github:https://github.com/Fredlxy/TVRecyclerView

相關文章