Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package jp.radiko.testasyncalertdialog
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
class MainActivity : AppCompatActivity(), CoroutineScope {
enum class AlertResult {
Ok,
Cancel,
}
private suspend fun myAlert(): AlertResult = suspendCoroutine { cont ->
AlertDialog.Builder(this@MainActivity)
.setMessage("this is a test.")
.setPositiveButton("Ok") { _, _ -> cont.resume(AlertResult.Ok) }
.setNegativeButton("Cancel") { _, _ -> cont.resume(AlertResult.Cancel) }
.setOnCancelListener { cont.resume(AlertResult.Cancel) }
.show()
}
private lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
job = Job()
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.btnHello).setOnClickListener {
launch {
val result = myAlert()
Toast.makeText(this@MainActivity, result.toString(), Toast.LENGTH_SHORT)
.show()
// OKボタン
// キャンセルボタン
// 戻るボタンでキャンセル
// アクティビティを閉じてjobをキャンセル (再現手順は?)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.