这里有几个相关的帖子,但没有一个是完全相同的情况/没有一个解决方案对我有用。
我有一个从 Firebase 加载一些数据的 RecyclerView。我正在使用自定义适配器。问题是当 View 加载时,它加载在 RecyclerView 的中间。然后我将不得不手动向上滚动到顶部。
我的布局很简单:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/grey"
android:layout_marginBottom="50dp"
>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recycler_view_feed"
android:layout_marginTop="10dp"
>
</android.support.v7.widget.RecyclerView>
</LinearLayout>
从 Firebase 加载我的自定义对象后,我像这样设置 RecyclerView(这是在从 onCreateView 调用的方法中(它是一个 fragment )):
CompleteWorkoutRecyclerAdapter adapter = new CompleteWorkoutRecyclerAdapter(list, getContext(),
getActivity());
mRecyclerView.setAdapter(adapter);
mRecyclerView.setHasFixedSize(false);
linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, true);
mRecyclerView.setLayoutManager(linearLayoutManager);
我已经尝试了这些方法来解决这个问题,但没有成功:
linearLayoutManager.scrollToPosition(0);
和
mRecyclerView.scrollToPosition(0);
和
android:focusableInTouchMode="true"
感谢阅读。如果你们需要更多代码,我可以发布您需要的任何代码
最佳答案
首先把你的xml改成这个
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/recycler_view_feed"
android:layout_marginTop="10dp">
然后是代码
mRecyclerView.setHasFixedSize(false);
linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(linearLayoutManager);
CompleteWorkoutRecyclerAdapter adapter = new CompleteWorkoutRecyclerAdapter(list, getContext(),
getActivity());
mRecyclerView.setAdapter(adapter);
将适配器中行布局的高度更改为 wrap_content
关于java - Android - RecyclerView 从中间而不是顶部开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45541202/