如何从 ScrollView 中的 RecyclerView 移除焦点?

How to remove focus from RecyclerView inside ScrollView?

我有一个包含 ImageView 和 RecyclerView 的 Scrollview。 如果导航抽屉打开然后关闭 RecyclerView 自动滚动到顶部,如何停止这个?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/scrollViewMain"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

       <ImageView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:id="@+id/imageView_main_icons_line"
           android:src="@drawable/main_line" />

              ...


       <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView_activity_main_passenger_log"
            android:paddingBottom="2dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>
</ScrollView>
</RelativeLayout>

从这里 Android Dev Doc.

查看 clearFocus()

您可以为导航抽屉设置 DrawerListener 并使用 onDrawerStateChanged() 或 [=11 中的一些其他选项=] 在 RecyclerView.

上调用 clearFocus()

这个问题是因为recyclerView有默认焦点。

Solution

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:descendantFocusability="blocksDescendants"
    android:orientation="vertical">

android:descendantFocusability="blocksDescendants" 添加到您的 scrollView 直接布局

那是因为 RecyclerView 总是设置:

setFocusableInTouchMode(true);

这是硬编码在它的构造函数中。

因此,如果您在 XML 中为 RecyclerView

应用这些属性
android:focusable="false"
android:focudeableInTouchMode="false"

那是没用的,你最终会得到 recycleView.isFocusable() == true...

所以最优雅的解决方案是为 RecyclerView 的父级禁用 focusable。

<LinearLayout
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:descendantFocusability="blocksDescendants"
    ...
    >
    <android.support.v7.widget.RecyclerView
        ...
    />
/>

或者您可以简单地设置 Focusable(false)

只需在您的线性布局中添加以下代码,100% 有效` android:descendantFocusability="blocksDescendants"

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

    <LinearLayout
        android:descendantFocusability="blocksDescendants"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

添加 android:descendantFocusability="blocksDescendants" 可以限制滚动到 recylerview,但如果您的布局中有编辑文本,此 属性 也可以阻止该特定编辑文本的焦点。因此,如果您正在使用此 属性,请确保在加载布局后在 kotlin/java class 中删除此 属性。

parentLayout?.descendantFocusability = FOCUS_BEFORE_DESCENDANTS (view as ViewGroup).descendantFocusability = FOCUS_BEFORE_DESCENDANTS