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 5 years have passed since last update.

AndrodのToast

Posted at

Toast

Toastは短いメッセージをユーザーに知らせるもので、自動的に消えます。Toast自身がユーザーの入力や操作を待つことはしません。
ユーザーの操作に対するフィードバックを伝える感じです。

ソースコード

ToastActivity.kt
class ToastActivity : AppCompatActivity() {

    private lateinit var helloTextView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_toast)

        helloTextView = findViewById(R.id.helloTextView)
        helloTextView.setOnClickListener {
            val toast = Toast.makeText(applicationContext, "Hello Toast", Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.TOP or Gravity.START, 0, 0)
            toast.show()
        }
    }
}

使い方

Toast.makeText(applicationContext, "Hello Toast", Toast.LENGTH_SHORT).show()
基本的にこれだけです。
**makeText()**でToastを作成し、**show()**で画面に表示します。

makeText()について

ここでは3つのものを引数として与えています。

context: Context!

普通はApplicationかActivityのインスタンスです。
確認する限りapplicationContextでもapplicationでもthisでも動作します。何を指定するべきか詳しくはわかっていませんが、公式ドキュメントの例に則ってapplicationContextがいいかと思います。
※Android Javaの場合はおそらく匿名クラスの中で使うことになると思うので、thisView.OnClickListnerを指しコンパイルエラーとなります。

なぜToastがContextを取るかというと、Viewとして管理してもらう必要があったり、リソースIDにアクセスする必要があったりするためです。

text: CharSequence!

表示するテキストです。ここではベタに書いていますが、リソースIDも受け付けるのでそちらを指定する方がいいです。

duration: Int

表示される持続時間です。Toast.LENGTH_SHORTToast.LENGTH_LONGの2種類しかありません。ソースを追ってみるとそれぞれ4秒と7秒を指定しているように見えますが、体感としては2秒半と4秒くらいで消えます。

setGravity()について

デフォルトでは画面下にToastは表示されますが、このメソッドを使って配置を変更することができます。
例えば第一引数にGravity.TOP or Gravity.STARTと指定することで、画面左上に表示されます。
(なんか論理和使っていますね)
Gravity.TOP or Gravity.START or Gravity.BOTTOMと指定してしまうと、画面左側に縦長に伸びたToastが表示されてしまいます。

第二引数と第三引数はそれぞれX座標とY座標の調整です。
pixel単位で移動でき、マイナスの数値を指定して逆方向に動きます。

参考

トーストの概要
Toast | Android Developers
Android Programming: The Big Nerd Ranch Guide (3rd Edition) (Big Nerd Ranch Guides)

補足

いろいろ調べたあとにMaterial Design的には「snackbarのほうがいいぜ」って書いてあって悲しい。
https://material.io/develop/android/components/snackbar/

Android also provides a Toast class with a similar API that can be used for displaying system-level notifications. Generally, snackbars are the preferred mechanism for displaying feedback messages to users, as they can be displayed in the context of the UI where the action occurred. Reserve Toast for cases where this cannot be done.

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?