0

這是我的xml代碼。如何在NestedScrollView內的RecyclerView中scrollTo(x,y)?

<android.support.v4.widget.NestedScrollView 
     android:id="@+id/nav_scroll" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 

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

      <include layout="@layout/nav_header_main" /> 

      <android.support.v7.widget.RecyclerView 
       android:id="@+id/nav_list" 
       android:layout_width="match_parent" 
       android:layout_height="@dimen/weight_based_height" 
       android:layout_weight="1" 
       android:nestedScrollingEnabled="false"/> 
     </LinearLayout> 

    </android.support.v4.widget.NestedScrollView> 

我已經試過

navigationScroll.scrollTo(0, 200); 
    navigationScroll.smoothScrollTo(0, 200); 
    navigationRecycler.scrollTo(0, 200); 
    navigationRecycler.smoothScrollTo(0, 200) 

和他們沒有工作。沒有任何反應,沒有任何數量的卷軸,納達。

但有趣的是,當我做這個

navigationScroll.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() { 
     @Override 
     public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { 
      if (scrollY == 0) { 
       navigationScroll.scrollTo(0, 150); 
      } 
     } 
    }); 

navigationScroll.scrollTo(0, 150);作品。你們如何認爲我可以讓它工作而不必把它放在聽衆的?

編輯: 好吧,我的NestedScrollView是在我的DrawerLayout裏面。一旦我把它放入onDrawerOpened這樣,我就得到了scrollTo()方法。

toggle = new ActionBarDrawerToggle(
     this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close){ 
     @Override 
     public void onDrawerClosed(View drawerView) { 
      super.onDrawerClosed(drawerView); 
     } 

     @Override 
     public void onDrawerOpened(View drawerView) { 
      super.onDrawerOpened(drawerView); 
      // Scroll to current item 
      navigationScroll.smoothScrollTo(0,200); 
     } 

    }; 
    drawer.setDrawerListener(toggle); 

回答

0

你把那些方法放在哪裏(即在哪個Activity/Fragment生命週期方法中)?在實際呈現視圖之前,您可能會調用這些方法。在這種情況下,您應該將這些設置爲不同的生命週期方法,或者使用post(Runnable r)推遲它們。

+0

我終於明白了,但感謝您的意見! – Isaiah

相關問題