如何在Android TV上的RecyclerView中实现滚动?

BAr*_*ell 5 android-tv android-recyclerview

我有一个应用程序,我需要适应Android TV.此应用程序包含水平RecyclerView,当我按遥控器上的D-pad按钮时它不会滚动.我找到了这个解决方案,但它崩溃了.这是代码:

<ru.myapp.package.HorizontalPersistentFocusWrapper
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
       <android.support.v7.widget.RecyclerView
           android:id="@+id/recycler_view"
           android:layout_width="match_parent"
           android:layout_height="250dp"
           android:background="@null"
           android:scrollbars="none"/>
</ru.myapp.package.HorizontalPersistentFocusWrapper>
Run Code Online (Sandbox Code Playgroud)

Horizo​​ntalPersistentFocusWrapper与PersistentFocusWrapper相同,但mPersistFocusVertical = false;

在这个地方发生崩溃:

@Override
    public void requestChildFocus(View child, View focused) {
        super.requestChildFocus(child, focused);
        View view = focused;
        while (view != null && view.getParent() != child) {
            view = (View) view.getParent(); <<<------ Crash here
        }
        mSelectedPosition = view == null ? -1 : ((ViewGroup) child).indexOfChild(view);
        if (DEBUG) Log.v(TAG, "requestChildFocus focused " + focused + " mSelectedPosition " + mSelectedPosition);
    }
Run Code Online (Sandbox Code Playgroud)

崩溃堆栈跟踪:

java.lang.ClassCastException: android.view.ViewRootImpl cannot be cast to android.view.View
         at ru.myapp.package.HorizontalPersistentFocusWrapper.requestChildFocus(HorizontalPersistentFocusWrapper.java:108)
         at android.view.View.handleFocusGainInternal(View.java:5465)
         at android.view.ViewGroup.handleFocusGainInternal(ViewGroup.java:714)
         at android.view.View.requestFocusNoSearch(View.java:8470)
         at android.view.View.requestFocus(View.java:8449)
         at android.view.ViewGroup.requestFocus(ViewGroup.java:2747)
         at android.view.View.requestFocus(View.java:8416)
         at android.support.v4.widget.NestedScrollView.arrowScroll(NestedScrollView.java:1222)
         at android.support.v4.widget.NestedScrollView.executeKeyEvent(NestedScrollView.java:551)
         at android.support.v4.widget.NestedScrollView.dispatchKeyEvent(NestedScrollView.java:512)
         at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1640)
         at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1640)
Run Code Online (Sandbox Code Playgroud)

Yan*_*000 5

使用最新版本的RecyclerView。或至少使用
com.android.support:recyclerview-v7:23.2.0
此链接了解更多信息:https :
//code.google.com/p/android/issues/detail?id=190526&thanks=190526&ts=1445108573

现在是重要部分:
RecyclerView的新版本开始遵守其子级规则(例如高度和宽度)。您必须在子项XML中将根视图设置为:
android:focusable="true"

现在,滚动将按预期进行。