0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Android ポップアップの表示時間をデフォルトより長くor短くする 【Kotlin】【Coroutine】

Last updated at Posted at 2022-06-14

はじめに

Androidには標準で、ポップアップ表示を行うToastというものがあります。
(参考:https://developer.android.com/guide/topics/ui/notifiers/toasts
しかし、こいつ表示時間が自由に選べません。
「LENGTH_SHORT」=2秒か「LENGTH_LONG」=3.5秒
の二つしか値を取れないのです。

今回は、もっと短くor長くトーストを表示したい方に向けて
kotlinで自作のcustomToastクラスを作ってみました。

ちなみにAsyncTaskで実装したコードは割とあるのですが
Android11で非推奨になっているため今回はCoroutineで実装しています。

前提

エディター:Android Studio
言語:Kotlin

coroutineを使うのでbuild.gradleにcoroutineを追加して、syncProjectしておいてください。

dependencies {
    implementation( "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.0")
    // 以下は、元々の記述
}

作ったもの

早速ですがコードです。
適当なフォルダの下にCustomToast.ktというファイルを作成して、以下を貼り付けます。

import android.content.Context
import android.os.Handler
import android.util.Log
import android.widget.Toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class CustomToast : Runnable {
    private var toast: Toast? = null
    private var duration: Long = 0
    private val handler = Handler()
    suspend fun show() {
        if (duration > 2000) {
            var i = 0
            while (i < duration - 2000) {
                handler.postDelayed(this, i.toLong())
                i += 2000
            }
            handler.postDelayed(this, duration - 2000)
        } else {
            this.execute()
        }
    }

    override fun run() {
        toast!!.show()
    }

    private suspend fun execute() {
        try {
            withContext(Dispatchers.Main) {
                toast!!.show()
            }
            Thread.sleep(duration)
            withContext(Dispatchers.Main) {
                toast!!.cancel()
            }
        } catch (e: Exception) {
            Log.e(localClassName, "ここにキャンセル時の処理を記述", e)
        }
    }


    companion object {
        fun makeText(context: Context?, text: CharSequence?, duration: Long): CustomToast {
            val ct = CustomToast()
            ct.toast = Toast.makeText(context, text, Toast.LENGTH_SHORT)
            ct.duration = duration
            return ct
        }
    }

呼び出し側は適切なスコープから呼び出してください。

// 例
viewModelScope.launch {
  customToast.makeText(context, "表示したい文字列", "表示したい時間(ミリ秒)").show()
}

終わりに

一旦、この記事はここまでで公開しますが
LGTMなどの反応が多ければ解説記事書きます。

参考資料

  1. 公式のToastのページ https://developer.android.com/reference/android/widget/Toast
  2. javaでの実装例
    https://tech.pjin.jp/blog/2012/08/13/android-tipstoast%E3%81%AE%E8%A1%A8%E7%A4%BA%E6%99%82%E9%96%93%E3%82%92%E9%95%B7%E3%81%8F%E7%9F%AD%E3%81%8F%E3%81%99%E3%82%8B/
  3. AsyncTaskからCoroutineへの書き換え
    https://re-engines.com/2021/03/12/android-11%E3%81%A7deprecated%E3%81%AB%E3%81%AA%E3%81%A3%E3%81%9Fasynctask%E5%AF%BE%E5%BF%9Ckotlin%E7%B7%A8/
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?