Android Toast 使用

2021-03-11  本文已影响0人  潘傑威

基本的使用

val text = "Hello toast!"
val duration = Toast.LENGTH_SHORT

val toast = Toast.makeText(applicationContext, text, duration)
toast.show()

或者

Toast.makeText(context, text, duration).show()

設定顯示位置

toast.setGravity(Gravity.TOP or Gravity.LEFT, 0, 0)

自定義自己Toast

  1. xml (saved as layout/custom_toast.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/custom_toast_container"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="8dp"
              android:background="#DAAA"
              >
    <ImageView android:src="@drawable/droid"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_marginRight="8dp"
               />
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textColor="#FFF"
              />
</LinearLayout>
val inflater = layoutInflater
val container: ViewGroup = findViewById(R.id.custom_toast_container)
val layout: ViewGroup = inflater.inflate(R.layout.custom_toast, container)
val text: TextView = layout.findViewById(R.id.text)
text.text = "This is a custom toast"
with (Toast(applicationContext)) {
    setGravity(Gravity.CENTER_VERTICAL, 0, 0)
    duration = Toast.LENGTH_LONG
    view = layout
    show()
}

基本上是這樣 如有其他方式再更新

上一篇 下一篇

猜你喜欢

热点阅读