App啟動頁倒計時功能


轉載請注明出處:http://www.cnblogs.com/cnwutianhao/p/6753418.html 

 

示例代碼采用 RxJava + RxLifecycle + Data-Binding 模式編寫

示例圖:

話不多說,實現方式如下:

1.導入依賴庫

① RxJava: Reactive Extensions for the JVM

compile 'io.reactivex:rxjava:1.2.9'
compile 'io.reactivex:rxandroid:1.2.1'

② RxLifecycle

compile 'com.trello:rxlifecycle:1.0'
compile 'com.trello:rxlifecycle-components:1.0'

③ Data-Binding

dataBinding {
    enabled = true
}

 

2.代碼編寫(關鍵代碼)

① 自定義接口View

public interface BaseView {

    <T> LifecycleTransformer<T> bindToLife();

}

 

② 創建一個Helper類,用來進行倒計時操作

public final class RxHelper {

    private RxHelper() {
        throw new AssertionError();
    }

    /**
     * 倒計時
     */
    public static Observable<Integer> countdown(int time) {
        if (time < 0) {
            time = 0;
        }
        final int countTime = time;

        return Observable.interval(0, 1, TimeUnit.SECONDS)
                .map(new Func1<Long, Integer>() {
                    @Override
                    public Integer call(Long increaseTime) {
                        return countTime - increaseTime.intValue();
                    }
                })
                .take(countTime + 1)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread());
    }

}

 

③ 自定義方法:實現異步加載

private void init() {
    RxHelper.countdown(5)
            .compose(this.<Integer>bindToLife())
            .subscribe(new Subscriber<Integer>() {
                @Override
                public void onCompleted() {
                    doSkip();
                }

                @Override
                public void onError(Throwable e) {
                    doSkip();
                }

                @Override
                public void onNext(Integer integer) {
                    mBinding.sbSkip.setText("跳過 " + integer);
                }
            });
}

 

④ 自定義方法:實現跳轉

private void doSkip() {
    if (!mIsSkip) {
        mIsSkip = true;
        finish();
        startActivity(new Intent(SplashActivity.this, MainActivity.class));
        overridePendingTransition(R.anim.hold, R.anim.zoom_in_exit);
    }
}

 

⑤ 設置主題樣式為全屏

<style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowFullscreen">true</item>
</style>

 

示例Demo下載:App啟動頁倒計時功能

 

關注我的新浪微博,請認准黃V認證,獲取最新安卓開發資訊。

關注科技評論家,領略科技、創新、教育以及最大化人類智慧與想象力!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM