appbarlayout.addOnOffsetChangedListener失效问题

论坛 期权论坛 脚本     
已经匿名di用户   2022-5-29 19:38   5155   0

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

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP