Handler弱引用举例(ViewPager的自动播放)

前提该代码在HomeFragment中完成:

 private int page = 0;

    //Handler的弱引用
    private static class MyHandler extends Handler {
        private WeakReference<HomeFragment> weakReference;

        public MyHandler(HomeFragment fragment) {
            weakReference = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            HomeFragment fragment = weakReference.get();
            if (null != fragment) {
                if (msg.what == 0) {
                    fragment.viewPager.setCurrentItem(fragment.page % fragment.list.size());
                }
            }
        }
    }

    private MyHandler myHandler = new MyHandler(this);
 private boolean flag = true;//用于自动播放循环条件,一直true,销毁方法里改为false

    //viewPager自动播放
    private void autoBanner() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag) {
                    try {
                        Thread.sleep(2500);
                        page++;
                        myHandler.sendEmptyMessage(0);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        flag = false;
    }

你可能感兴趣的:(Handler弱引用举例(ViewPager的自动播放))