Skip to content

Instantly share code, notes, and snippets.

@TheLittleNaruto
Last active July 21, 2020 09:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheLittleNaruto/6fc8f6a2b0d0583a240bd78313ba83bc to your computer and use it in GitHub Desktop.
Save TheLittleNaruto/6fc8f6a2b0d0583a240bd78313ba83bc to your computer and use it in GitHub Desktop.
Custom Toast Helper
/*
* Copyright (C) 2019 @author TheLittleNaruto
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import android.widget.TextView
import android.widget.Toast
class CustomToast @SuppressLint("ShowToast")
private constructor(context: Context) {
private val toastInstance: Toast? = Toast.makeText(context, "", Toast.LENGTH_LONG)
fun show() {
toastInstance?.show()
}
class Builder(context: Context) {
private var toast: CustomToast = CustomToast(context)
private var toastView: View
private var toastTextView: TextView
init {
toastView = toast.toastInstance!!.view
toastTextView = toastView.findViewById(android.R.id.message)
}
fun setText(message: String): Builder {
toastTextView.text = message
return this
}
fun setTextSize(size: Int): Builder {
toastTextView.textSize = size.toFloat()
return this
}
fun setTextColor(color: Int): Builder {
toastTextView.setTextColor(color)
return this
}
fun setDrawables(left: Int, right: Int, top: Int, bottom: Int): Builder {
toastTextView.setCompoundDrawablesWithIntrinsicBounds(
left, right, top, bottom
)
return this
}
fun setGravity(gravity: Int): Builder {
toastTextView.gravity = gravity
return this
}
fun setDrawablePadding(padding: Int): Builder {
toastTextView.compoundDrawablePadding = padding
return this
}
fun setBackgroundColor(color: Int): Builder {
toastView.setBackgroundColor(color)
return this
}
fun setDuration(duration: Int): Builder {
toast.toastInstance!!.duration = duration
return this
}
fun apply(): CustomToast{
return toast
}
}
}
val customToast = CustomToast.Builder(context)
.setText("Hello")
.setTextSize(25)
.setBackgroundColor(R.color.colorPrimary)
.setTextColor(android.R.color.black)
.setDuration(Toast.LENGTH_SHORT)
.setGravity(Gravity.CENTER)
.apply()
customToast.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment