Androidにおける遅延実行の実装方法
今回はAndroidにおける遅延実行の実装方法について紹介する。
遅延実行とは、名前から予想できる通り、遅らせて処理を実行することである。
<方法概要>
Handlerクラスの「postDelayed」メソッドを使用して、指定した時間後に、指定した処理を実行する。
postDelayedメソッドの定義は下記の通りである。
postDelayed (Runnable r, long delayMillis)
第1引数に「遅らせて実行したい処理」をRunnable型で指定し、第2引数に「遅らせたい時間」をミリ秒単位で指定する。
<サンプルコード>
以下のサンプルコードは画面上の文字を3秒後に変更するものである。
MainActivity.java
package biz.accele.sampledelay; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView txt1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txt1 = (TextView)findViewById(R.id.txt1); // Handlerクラスをインスタンス化し、postDelayedメソッドを呼んでいる new Handler().postDelayed(new Runnable() { // Runnable型のインスタンス化と定義 @Override public void run() { // 遅らせて実行したい処理 txt1.setText("本日は晴天なり"); } }, 3000); // 遅らせたい時間(ミリ秒) 3000ミリ秒 -> 3秒 } }
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:id="@+id/txt1" android:text="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>