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

新手上路,请多包涵

我有一个包含 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>

原文由 Samad 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 745
2 个回答

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

解决方案

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

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

原文由 Rahul Devanavar 发布,翻译遵循 CC BY-SA 3.0 许可协议

那是因为 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
        ...
    />
/>

或者你可以简单地 setFocusable(false)

原文由 landerlyoung 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题