在AppBarLayout中使用addOnOffsetChangedListener()方法,根据AppBar的偏移量来动态改变View的宽度。
示例代码如下所示:
//获取目标View和AppBarLayout final View targetView = findViewById(R.id.target_view); AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
//AppBarLayout的偏移量监听 appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() { @Override public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { //获取AppBarLayout总高度 int totalScrollRange = appBarLayout.getTotalScrollRange();
//计算滚动比例(取绝对值)
float proportion = (float) Math.abs(verticalOffset) / (float) totalScrollRange;
//根据比例改变View的宽度
targetView.getLayoutParams().width = (int) (proportion * 500); //此处500为View的初始宽度
targetView.requestLayout(); //请求重新布局
}
});
以上代码在AppBar滚动时,会根据滚动比例动态改变View的宽度,从而实现动画效果。
下一篇:AppBar滚动视图行为