自定義Toast

自定義Toast

平時通常只用默認的Toast,使用Toast.makeTest()方法調用,默認的風格是白字半透明灰框,常常與app的主題顏色不符,因此須要自定義Toast.效果圖:html

這裏寫圖片描述

顯示定義須要的佈局文件:layout/custom_toast.xmljava

<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>

注意root view 的I必須設置id(接下來代碼用到,此時爲custom_toast_container)android

接下來是kotlin代碼(根據android官網,手動將Java代碼改成Kotliin代碼)安全

class ToastActivity:AppCompatActivity(){


  override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      var layoutInflater:LayoutInflater = layoutInflater


      //這裏須要一個安全類型轉換as?, 否則編譯沒法經過,由於ViewGroup是not null類型,
      //而findViewById(R.id.custom_toast_container)可能爲null,因此不能直接用as
      var layout: View = layoutInflater.inflate(R.layout
              .custom_toast, findViewById(R.id.custom_toast_container) as? ViewGroup)

      val text:TextView = layout.findViewById(R.id.text) as TextView
      text.setText("This is a custom toast")

      //這個若是是java語法,則須要調用getApplicationContext,
      val toast = Toast(applicationContext)
      toast.setGravity(Gravity.CENTER_VERTICAL, 0, 300)//設置位置
      toast.duration = Toast.LENGTH_LONG
      toast.view = layout//java:toast.setView(layout);
      toast.show()
  }
}

代碼都是官方文檔拿過來的,裏面是Java代碼:
https://developer.android.com...app

相關文章
相關標籤/搜索