簡體   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