class MyToast(val context: Context) : Toast(context) {
private var toastText: String = ""
private val textView: TextView = TextView(context).apply {
setBackgroundColor(ContextCompat.getColor(context, R.color.color_4D4D4D))
gravity = Gravity.CENTER
setTextColor(ContextCompat.getColor(context, android.R.color.white))
setTextIsSelectable(false)
outlineProvider = object : ViewOutlineProvider() {
override fun getOutline(view: View, outline: Outline) {
//圆角
outline.setRoundRect(0, 0, view.width, view.height, view.width / 2f)
}
}
//将视图裁剪至其轮廓区域
clipToOutline = true
val params = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT
)
layoutParams = params
val d1 = SizeUtil.dp2px(16f).toInt()
val d2 = SizeUtil.dp2px(9f).toInt()
setPadding(d1, d2, d1, d2)
}
init {
view = FrameLayout(context).apply {
addView(textView)
systemUiVisibility = SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
}
setGravity(
Gravity.BOTTOM + Gravity.CENTER_HORIZONTAL, 0,
SizeUtil.dp2px(64f).toInt()
)
}
fun setToastText(text: String): MyToast {
toastText = text
return this
}
fun setToastText(@StringRes stringRes: Int): MyToast {
toastText = context.getString(stringRes)
return this
}
override fun getDuration(): Int = LENGTH_SHORT
override fun show() {
textView.text = toastText
super.show()
}
}
android 根据UI需求自定义一个Toast样式
于 2022-12-10 14:11:07 首次发布