在 Kotlin 我使用这个:
private lateinit var toast: Toast
fun showToast(@StringRes stringId: Int, toastLength: Int = Toast.LENGTH_SHORT)
{
if (this::toast.isInitialized)
{
toast.cancel()
}
toast = Toast.makeText(
requireContext(),
getString(stringId),
toastLength
)
toast.show()
}
或者当在许多片段中使用它时,可以扩展Fragment
类,因此函数showToast
不必在每个片段中。
open class OneToastFragment : Fragment()
{
private lateinit var toast: Toast
fun showToast(@StringRes stringId: Int, toastLength: Int = Toast.LENGTH_SHORT)
{
if (this::toast.isInitialized)
{
toast.cancel()
}
toast = Toast.makeText(
requireContext(),
getString(stringId),
toastLength
)
toast.show()
}
}
此外,使用Toasty 库也很容易。
摇篮项目:
repositories {
...
maven { url "https://jitpack.io" }
}
Gradle 模块应用程序:
dependencies {
...
implementation 'com.github.GrenderG:Toasty:1.4.2'
}
Activity 类中的 onCreate:
Toasty.Config.getInstance().allowQueue(false).apply(); // set this to avoid toast acumulations
//Test:
int x = 0;
Toasty.info(this, Integer.toString(x++), Toast.LENGTH_SHORT, true).show();
Toasty.info(this, Integer.toString(x++), Toast.LENGTH_SHORT, true).show();
Toasty.info(this, Integer.toString(x++), Toast.LENGTH_SHORT, true).show();
//This will only show a toast with message `2`