Search code examples
androidnavigationviewandroid-navigationview

Scroll particular menuItem to top in navigationView when onDrawerOpened() called


I am using NavigationView (android.support.design.widget.NavigationView) in DrawerLayout. I am wondering if there is anyway to scroll at particular item programmatically, when user open the drawer. (while onDrawerOpened() called in activity)

For instance, when user opens the drawer, I want MenuItem "action_feedback" at the top of DrawerLayout (Scrolled to Top).

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
    <item
        android:id="@+id/action_current_list"
        android:checked="true"
        android:icon="@drawable/ic_current_list"
        android:title="@string/current_list" />
    <item
        android:id="@+id/action_manage_lists"
        android:icon="@drawable/ic_my_lists"
        android:title="@string/my_lists" />
    <item
        android:id="@+id/action_search_products"
        android:icon="@drawable/ic_search_black_24dp"
        android:title="@string/search_products" />
    <item
        android:id="@+id/action_deals"
        android:icon="@drawable/ic_product_promo"
        android:title="@string/deals" />
</group>
<group android:id="@+id/nav_footer"
        android:checkableBehavior="single">
    <item
        android:id="@+id/action_feedback"
        android:icon="@drawable/ic_feeback"
        android:title="@string/feedback" />
    <item
        android:id="@+id/action_sign_out"
        android:icon="@drawable/ic_sign_out"
        android:title="@string/sign_out" />
</group>

Earlier I had Custom Layout (ScrollView + ListView) in DrawerLayout, and It was possible using scrollView.scrollTo(x,y).

Thanks in advance.


Solution

  • private NavigationView vNavigation;
    
    // ...
    
    @Override
    public void onDrawerOpened(View drawerView)
    {
        RecyclerView recyclerView = (RecyclerView)vNavigation.getChildAt(0);
        LinearLayoutManager layoutManager = (LinearLayoutManager)recyclerView.getLayoutManager();
        layoutManager.scrollToPositionWithOffset(4, 0);
    }