How do you display a Toast using Kotlin on Android?

前端 未结 15 2205
遇见更好的自我
遇见更好的自我 2021-01-30 16:08

In different Kotlin examples for Android I see toast("Some message...") or toastLong("Some long message"). For example:



        
15条回答
  •  生来不讨喜
    2021-01-30 16:16

    Download source code from here (Custom Toast In Android Kotlin )

    fun Toast.createToast(context: Context, message: String, gravity: Int, duration: Int, backgroucolor: String, imagebackgroud: Int) {
            val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
            /*first parameter is the layout you made
            second parameter is the root view in that xml
             */
            val layout = inflater.inflate(R.layout.custom_toast, (context as Activity).findViewById(R.id.custom_toast_container))
    
            layout.findViewById(R.id.tv_message).text = message
            layout.setBackgroundColor(Color.parseColor(backgroucolor))
            layout.findViewById(R.id.iv_image).iv_image.setImageResource(imagebackgroud)
            setGravity(gravity, 0, 100)
            setDuration(Toast.LENGTH_LONG);
    
            setView(layout);
            show()
        }
    

    Thanks!

提交回复
热议问题