我们在开发过程经常会组合使用RecyclerView和ScrollView,但是它经常显示不兼容,后面发现只要给RecyclerView的外层加上一个RelativeLayout 就可以解决该问题。特此记录一下。
xml页面:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants"><!--这句很重要,不能少-->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/dp_5"
android:layout_marginTop="@dimen/dp_10"
android:layout_marginRight="@dimen/dp_5" />
</RelativeLayout>
</ScrollView>
MainActivity:
RecyclerView recyclerView = findViewById(R.id.recyclerView);
GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setNestedScrollingEnabled(false);//禁止recyclerView嵌套滑动
至此,就可以实现想要的效果了。