繁体   English   中英

带有ViewPager的片段上的Android CountDownTimer

[英]Android CountDownTimer on Fragment with ViewPager

我是android开发的新手。

我开发了一个ViewPager,以在用户单击下一步按钮时显示不同的图像。

但是我想在显示新图像时启动CountDownTimer。

我怎样才能做到这一点?

我的代码目前是:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        int imgNumber = mPageNumber + 1;
        String strImg = "ss0" + imgNumber;
        ViewGroup rootView = (ViewGroup) inflater.inflate(
                R.layout.fragment_ssstretch4_split, container, false);

        // Set the title view to show the page number.
        ((TextView) rootView.findViewById(R.id.text1)).setText(
                getString(R.string.title_activity_ssstretch4_split, mPageNumber + 1));

        //Mettre l'image
        int idImg = getResources().getIdentifier("com.trainwithcoachminiil.app:drawable/" + strImg, null, null);
        ((ImageView) rootView.findViewById(R.id.imgSS)).setImageResource(idImg);

        //Lancer le timer
        textActivity = (TextView) rootView.findViewById(R.id.textActivity);
        textCountDown = (TextView) rootView.findViewById(R.id.textCountDown);
        countDownTimerPrepare = new CountDownTimerActivityPrepare(startTimePrepare, interval);
        textActivity.setText(R.string.activityPrepare);
        textCountDown.setText(String.valueOf(startTimePrepare/1000));
        countDownTimerPrepare.start();

        return rootView;
    }

但是,当我转到下一页时,我的倒数计时器仍在运行,因此出现奇怪的现象。

非常感谢您能告诉我该怎么做。

Fragment onDestroy上调用yourCountDownTimer.cancel()

Viewpager一次至少加载两个pages/Fragment 它将启动您的第二个Fragment / page count计时器

因此,当您的fragment is visible时,您应该启动计时器。 首先使用setUserVisiblesetMenuVisibility委托处理片段可见性。 然后启动您的countDown计时器。 并在DestroyView上取消计时器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM