Skip to content

Instantly share code, notes, and snippets.

@tateisu
Created July 7, 2019 08:51
Show Gist options
  • Save tateisu/fab0966e4541e2b2ccbfb4e8515cc9c5 to your computer and use it in GitHub Desktop.
Save tateisu/fab0966e4541e2b2ccbfb4e8515cc9c5 to your computer and use it in GitHub Desktop.
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