Androidで簡単にメッセージをユーザーに知らせるために Toast をよく使います。
Android 11以降はsetGravityでの位置調整ができなくなりました。
2021.1.1
Toast
アメリカではパーティの時に「Toast」と言うのが時々出てきます。乾杯の前に「ジョージの成功を祝って!」などと言う「短い祝辞」のことですね、パンの「トースト」ではありません
~閑話休題~
トーストを使う時は、
1 |
import android.widget.Toast |
をインポートします。
基本的な使い方は、
1 |
Toast.makeText(context, text, duration).show() |
引数のコンテキストとしては、applicationContext を入れます。
具体的に
1 |
Toast.makeText(applicationContext, "トーストメッセージ", Toast.LENGTH_LONG).show() |
LENGTH_LONG の代わりに SHORT にすると表示時間が短くなります。
Toastの位置を変更できなくなったと聞きますが、これが以前は位置調整を可能にしていたのです
1 2 |
// xOffset:横方向のオフセット, yOffset:横方向のオフセット setGravity( gravity: Int, xOffset: Int, yOffset: Int) |
これは非推奨でもないような微妙な扱いで、ビルドエラーにはならないがAndroid 11 からは機能しないというものです。Toast
Warning: Starting from Android Build.VERSION_CODES#R, for apps targeting API level Build.VERSION_CODES#R or higher,
this method is a no-op when called on text toasts.
つまりToastはレイアウトは決められた場所にしか表示されない
なので、レイアウトの設定も必要ありません(できません)
GoogleのサンプルコードなどではSnackbarが良く使われています。
サンプルコード:
ボタンをタップするとToastが表示されるという使用例です。
Toastには直接関係しませんが、ButtonのためにView Bindingを使っています
MainActivity.kt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
//package com.example.testtoast import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast // ViewBinding import com.example.testtoast.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val toastMessage = "トースト" binding.button.setOnClickListener{ val toast = Toast.makeText(applicationContext, toastMessage, Toast.LENGTH_LONG) toast.show() } } } |
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/button" android:text="@string/button" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> |
build.gradle (Module: …)
1 2 3 4 5 6 7 8 |
... android { ... buildFeatures { viewBinding true } } ... |
strings.xml
1 2 3 4 |
<resources> <string name="app_name">Your App Name</string> <string name="button">Button</string> </resources> |
とても簡単にできました。いつの間にかドロイド君のアイコンが付いていますが
JavaでToastはこのようになります
References:
Toasts | Android Developers
Toasts