亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Android 使用 RxJava2 實現(xiàn)倒計時功能的示例代碼

 更新時間:2018年03月08日 10:21:14   作者:tnnowu  
本篇文章主要介紹了Android 使用 RxJava2 實現(xiàn)倒計時功能的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

倒計時功能被廣泛運用在 App 啟動頁、短信驗證碼倒計時等,通常做法是起一個Handler ,在子線程里完成倒計時,如今這一做法有了替代品 —— RxJava ,RxJava是被行內一致認可的第三方開源庫,我們可以使用RxJava實現(xiàn)倒計時功能。

示例圖:


示例代碼:

導入必要的庫文件(Android支持庫和Reactivex系列支持庫)

implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'

implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
implementation 'io.reactivex.rxjava2:rxjava:2.1.10'

布局文件(很簡單,只有一個TextView)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context="com.haocent.android.countdown.MainActivity">

  <TextView
    android:id="@+id/tv_count_down"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:text="Hello World!" />

</android.support.constraint.ConstraintLayout>

實現(xiàn)倒計時功能(代碼清晰明了,也打出了相應的Log)

public class MainActivity extends AppCompatActivity {

  private static final String TAG = MainActivity.class.getSimpleName();

  private Disposable mDisposable;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    final TextView tvCountDown = findViewById(R.id.tv_count_down);

    // 倒計時 10s
    mDisposable = Flowable.intervalRange(0, 11, 0, 1, TimeUnit.SECONDS)
        .observeOn(AndroidSchedulers.mainThread())
        .doOnNext(new Consumer<Long>() {
          @Override
          public void accept(Long aLong) throws Exception {
            Log.d(TAG, "倒計時");

            tvCountDown.setText("倒計時 " + String.valueOf(10 - aLong) + " 秒");
          }
        })
        .doOnComplete(new Action() {
          @Override
          public void run() throws Exception {
            Log.d(TAG, "倒計時完畢");

            Toast.makeText(MainActivity.this, "倒計時完畢", Toast.LENGTH_SHORT).show();
          }
        })
        .subscribe();
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();

    if (mDisposable != null) {
      mDisposable.dispose();
    }
  }
}

說明:① 在doOnNext里面做倒計時UI更改,在doOnComplete里面做倒計時完成之后的操作,如彈Toast或者跳轉等;② 我們調用重復執(zhí)行的方法,所以要在onDestroy方法中取消訂閱。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論