基本使用
在安卓中,简单的文本toast的使用方法很简单,一行代码就能搞定,比如在MainActivity中,我这样使用它:
class MainActivity : AppCompatActivity() {
// 证明一个触发toast的按钮
private lateinit var toastButton: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 初始化这个按钮
toastButton = findViewById(R.id.toast_button)
// 给这个按钮添加点击监听
toastButton.setOnClickListener {
// 弹出一个文本toast
Toast.makeText(this, "this is a text toast", Toast.LENGTH_SHORT).show()
}
}
}
当我们点击触发按钮,会在手机屏幕底部弹出toast,如下图:
更改显示位置
此时,新的需求是要求我们把toast的显示位置调整到手机屏幕的中部,我们该怎么办呢?通过下面的代码就可以搞定了:
Toast.makeText(this, R.string.correct_toast, Toast.LENGTH_SHORT).apply {
setGravity(Gravity.CENTER, 0, 0)
}.show()
这样,toast就会在屏幕的中央展示,如图:
如果你希望toast出现在屏幕的顶部,同样的,更改gravity的值为Gravity.TOP
就可以了。
但是要想实现这样的效果有一个前提就是你的项目的targetSdk
必须小于等于29。为什么会这样的,看一下官方文档我们就知道了:
所以如果你的targetSdk
大于29的话,你是没有办法通过设置gravity来改变text toast
的显示位置的。
targetSdk大于29时的注意事项
这里所谓的text toast
就是用上面的那种方法Toast.makeText(this, "this is a text toast", Toast.LENGTH_SHORT).show()
创建出来的toast。既然text toast
在targetSdk
大于29的情况下不可以改变位置,那别的类型的toast就可以了吗?是的,还有一种方法创建出来的toast在targetSdk大于29的情况下也可以改变显示位置,那就是simple toast。
使用simple toast我们需要先创建一个布局文件custom_toast.xml
:
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="this is a custom toast"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
然后就可以使用下面的代码创建:
Toast(this).also {
val view = LayoutInflater.from(this).inflate(R.layout.custom_toast, null)
it.setView(view)
it.duration = Toast.LENGTH_LONG
it.setGravity(Gravity.TOP, 0, 0)
}.show()
这样我们的toast就又可以显示在我们想要的位置上了。
你还可以给toast自定义背景,设置一些图片啊都可以,这个自己在布局文件中设置就可以了,跟设置页面的布局文件一样的:
setView()也deprecated了
在上面一个例子中我们用到了setView()
方法给toast设置布局,但是再看看官方文档,这个方法也被标记deprecated了。而且不允许在后台展示自定义toast了。
可能安卓就是想要我们都使用一个样式的toast,增加平台的统一性吧。这一点要告诉你们的设计师。
文章评论
文章不错,申请个友链哈