1. 程式人生 > >Android Scrollview嵌套RecyclerView導致滑動卡頓問題解決

Android Scrollview嵌套RecyclerView導致滑動卡頓問題解決

private 模式 gin -a ron android ole toc 禁止

一個比較長的界面一般都是Scrollview嵌套RecyclerView來解決.不過這樣的UI並不是我們開發人員想看到的,實際上嵌套之後.因為Scrollview和RecyclerView都是滑動控件.會有一點滑動上的沖突.導致滑動起來有些卡頓.這個時候.我們重寫一下LayoutManager就行了

例如:

[java] view plain copy
  1. LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false) {
  2. @Override
  3. public boolean canScrollVertically() {
  4. return false;
  5. }
  6. };
  7. recyclerview.setLayoutManager(linearLayoutManager);
  8. recyclerview.setAdapter(tempCommonAdapter);

如此.禁止掉RecyclerView的滑動.就能一如既往的流暢了

問題現象:

一個界面有多個RecyclerView或者其他超過一屏顯示的一些內容時,就需要要上下滾動了,就會需要在外面嵌套一個ScrollView,但是滑動過程不是很順暢,有卡頓的感覺。

解決方案:

禁止RecyclerView的滑動。

最簡單便捷的方法就是 [java] view plain copy
  1. linearLayoutManager = new LinearLayoutManager(context) {
  2. @Override
  3. public boolean canScrollVertically() {
  4. return false;
  5. }
  6. };

另外就是重寫LayoutManager了,以Grid模式舉例說明:

[java] view plain copy
  1. public class ScrollGridLayoutManager extends GridLayoutManager {
  2. private boolean isScrollEnabled = true;
  3. public ScrollGridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
  4. super(context, attrs, defStyleAttr, defStyleRes);
  5. }
  6. public ScrollGridLayoutManager(Context context, int spanCount) {
  7. super(context, spanCount);
  8. }
  9. public ScrollGridLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout) {
  10. super(context, spanCount, orientation, reverseLayout);
  11. }
  12. public void setScrollEnabled(boolean flag) {
  13. this.isScrollEnabled = flag;
  14. }
  15. @Override
  16. public boolean canScrollVertically() {
  17. //Similarly you can customize "canScrollHorizontally()" for managing horizontal scroll
  18. return isScrollEnabled && super.canScrollVertically();
  19. }
  20. }

Android Scrollview嵌套RecyclerView導致滑動卡頓問題解決