fra*_*ran 4 android scroll android-animation drawerlayout android-navigationview
我的活动NavigationView里面有一个DrawerLayout.
当用户点击NavigationView标题中的按钮时,我想滚动到顶部DrawerLayout/NavigationView带有动画.
看起来NavigationView和DrawerLayout没有提供获取实际滚动位置的方法(getScrollY()并且getScrollX()总是返回0),所以我不能这样做.
如何使用动画滚动到顶部?
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- My content -->
<android.support.design.widget.NavigationView
android:id="@+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/navigation_view_header"
app:menu="@menu/my_navigation_items" />
</android.support.v4.widget.DrawerLayout>
Run Code Online (Sandbox Code Playgroud)
你需要滚动NavigationMenuView.
在下面的代码中,当单击菜单中的任何项目时,它将滚动到顶部
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;
}
Run Code Online (Sandbox Code Playgroud)
编辑:如果你想要防止可能的变化,你可以在这里使用反射,如下所示:
// 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 |
SecurityException |
IllegalAccessException |
InvocationTargetException e) {
Log.d(TAG, "smoothScrollToPosition", e);
}
}
Run Code Online (Sandbox Code Playgroud)