由于Handler,片段没有附加到上下文?

问题描述 投票:-1回答:1

我做了一个Handler和一个Runnable等待2秒,直到动画开始,但是如果我将在这个时间离开应用程序,或者如果我将打开另一个Fragment,它会因为Handler而没有附加到上下文的异常片段崩溃。我能做什么?我尝试了很多来自网络的解决方案,但没有任何对我有用,没有使用动画的startoffset方法不是解决方案。谢谢你的帮助。

(如果我将Handler和Runnable从代码中删除它可以正常工作)

 Handler handler=new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                float dip = 20f;
                Resources r = getResources();
                float px = TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP,
                        dip,
                        r.getDisplayMetrics()
                );
                Animation outtoRight = new TranslateAnimation(
                        Animation.RELATIVE_TO_PARENT, 0,
                        Animation.RELATIVE_TO_PARENT, 0,
                        Animation.RELATIVE_TO_PARENT, 0,
                        Animation.ABSOLUTE, -(willkommen.getHeight() + px));
                outtoRight.setDuration(300);
                outtoRight.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        willkommen.setLayoutParams(params);
                        firstlaunchueberblick=true;
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
                grid.startAnimation(outtoRight);
                willkommen.startAnimation(outtoRight);
            }
        },2000);

这是片段里面的代码。

android-fragments runnable android-context android-handler
1个回答
-1
投票

handler.removeCallbacks(myRunnable);

这是解决方案。我读到我也可以传递null作为参数来删除所有回调,但这不起作用;

© www.soinside.com 2019 - 2024. All rights reserved.