=== 目次 ===
AlertDialogを動的に閉じる方法
AlertDialogを閉じるにはdismissメソッドを使用します。以下がサンプルコードです。
package com.areseitestproject;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
AlertDialog alertDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alertDialog = new AlertDialog.Builder(this)
.setMessage("TEST")
.show();
new Thread(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
alertDialog.dismiss();
}).start();
}
}
このコードではAlertDialog表示から3秒後にプログラムからAlertDialogを閉じています。
コツとしては、AlertDialog表示時にそのオブジェクトを取得しておくことです(17行目)。プログラムからAlertDialogを閉じるにはそのオブジェクトからdismissメソッドを実行すればOKです。