NavigationView navigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
@Override
public boolean onNavigationItemSelected(MenuItem item) {
//here will scroll to top
((NavigationMenuView)navigationView.getChildAt(0)).smoothScrollToPosition(0);
return true;
}
编辑:如果您想保护您不受沿途可能发生的变化的影响,您可以在这里使用反射,如下所示:
// try to scroll to the top of the navigation menu, if possible
if (navigationView.getChildCount() > 0) {
View childView = navigationView.getChildAt(0);
try {
Method scroll = childView.getClass().getMethod("smoothScrollToPosition", int.class);
scroll.invoke(childView, 0);
} catch (NoSuchMethodException |