appbarlayout.addOnOffsetChangedListener失效问题

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值