轉載請註明出處:http://www.cnblogs.com/cnwutianhao/p/6753418.html html
示例代碼採用 RxJava + RxLifecycle + Data-Binding 模式編寫java
示例圖:react
話很少說,實現方式以下:android
1.導入依賴庫異步
① RxJava: Reactive Extensions for the JVMide
compile 'io.reactivex:rxjava:1.2.9'
compile 'io.reactivex:rxandroid:1.2.1'
② RxLifecyclethis
compile 'com.trello:rxlifecycle:1.0'
compile 'com.trello:rxlifecycle-components:1.0'
③ Data-Bindingspa
dataBinding {
enabled = true
}
2.代碼編寫(關鍵代碼).net
① 自定義接口Viewcode
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認證,獲取最新安卓開發資訊。
關注科技評論家,領略科技、創新、教育以及最大化人類智慧與想象力!