问题
I'm trying to have a RecyclerView inside a ScrollView. My problem is that when i scroll the RecyclerView this is not "smooth": as soon as you release your finger the scrolling stops immediately.
My layout in the fragment is:
- Scrollview
- LinearLayout
- TextView
- RecyclerView
- Button
- LinearLayout
I tried disabling nested scrolling:
mRecyclerView.setNestedScrollingEnabled(false)
and wrapping content of mRecyclerView:
android:layout_height="wrap_content"
obtaining the smooth scrolling i wanted, but in this way the height of the RecyclerView is smaller than it should (and it doesn't scroll anymore, so i can't see some items).
I'm currently using support library 23.4.0 (i tried also 23.2.1, same problems)
Any help?
回答1:
This problem has wrecked my night. :)
Observations
When RecyclerView
is on the first screen (visible without scrolling), preceding views impact its height. When RecyclerView
is initially fully invisible (requires scrolling the whole screen down), its height is correct.
Reason
When LinearLayout
inside ScrollView
measures its children, it passes how many pixels left as a MeasureSpec
with mode UNSPECIFIED
.
RecyclerView
passes this spec to LayoutManager
, and it obeys passed height, if it is not null, even it is UNSPECIFIED
.
Solution
Extend RecyclerView
and override RecyclerView#onMeasure
and, when height measure spec is UNSPECIFIED
, just pass zero to super.onMeasure
.
Java:
@Override
protected void onMeasure(int widthSpec, int heightSpec) {
super.onMeasure(
widthSpec,
MeasureSpec.getMode(heightSpec) == MeasureSpec.UNSPECIFIED ? 0 : heightSpec
)
}
Kotlin:
override fun onMeasure(widthSpec: Int, heightSpec: Int) {
super.onMeasure(
widthSpec,
if (MeasureSpec.getMode(heightSpec) == MeasureSpec.UNSPECIFIED) 0
else heightSpec
)
}
来源:https://stackoverflow.com/questions/39267532/android-recyclerview-in-a-scrollview