AppBarLayout: onOffsetChanged stops being called after multiple scrolls
问题描述:
Using the CheeseSquare demo, if you register with AppBarLayout as an OnOffsetChangedListener, then onOffsetChanged is only called for a limited time. After multiple scrolls up and down, the method is never called.
-
Expected - onOffsetChanged should be called consistently for all registered listeners whenever the offset of AppBarLayout changes.
-
To reproduce: include this method in CheeseDetailActivity:
@Override
protected void onStart() {
super.onStart();
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
Log.d(“CheeseDetailActivity”, ” verticalOffset ” + verticalOffset);} });
}
原因:
Your problem is that AppBarLayout uses WeakReference to keep track of the offsetChanged listeners, and as soon as a GC is due your listener is collected.
解决方式:
@Override
protected void onStart() {
super.onStart();
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
appBarLayout.addOnOffsetChangedListener(this);
}
Then have CheesDetailActivity implement
AppBarLayout.OnOffsetChangedListener.
我在项目中是这样处理的:
@Override
protected void onResume() {
super.onResume();
mAppBarLayout.addOnOffsetChangedListener(this);
}
@Override
protected void onPause() {
super.onPause();
mAppBarLayout.removeOnOffsetChangedListener(this);
}
当然activity需要
implements AppBarLayout.OnOffsetChangedListener