Android
[Android] Toast 사용법(Kotlin)
Rd_Dev
2020. 8. 31. 23:41
Toast Message
특징
Toast는 안드로이드에서 이용 빈도가 가장 높은 다이얼로그 입니다.
- 화면 하단에 검정 바탕의 흰색 글이 잠깐 보이다가 사라지는 다이얼로그
- 사용자에게 메시지를 알리면서 사용자 행동을 방해하지 않는다.
1.일반적인 Toast Message 띄우기
public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
return makeText(context, null, text, duration);
}
//두 번째 매개변수는 토스트로 띄울 메시지,세 번째 매개변수는 토스트의 유지시간 입니다.
//Toast.LENGTH_SHORT = 3초, Toast.LENGTH_LONG = 5초 입니다.
Toast.makeText(this, "메시지", Toast.LENGTH_LONG).show()
2. 토스트 색상 변경 하기
1) 색상 코드로 변경하기
val toast : Toast = Toast.makeText(this,"메시지",Toast.LENGTH_SHORT)
toast.view.setBackgroundColor(ContextCompat.getColor(this,R.color.toastBackground))
toast.show()
2) CustomView로 바꾸기 + 토스트 위치 변경
toast_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_toast_root"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_toast_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
fun showCustomToast()
{
val toastView : View = layoutInflater.inflate(R.layout.toast_view,null)
toastView.findViewById<TextView>(R.id.tv_toast_message).apply {
text = "토스트 메시지2"
textSize = 15f
setTextColor(ContextCompat.getColor(this@MainActivity,R.color.toastText))
}
toastView.findViewById<LinearLayout>(R.id.ll_toast_root).apply {
setPadding(20,0,20,0)
setBackgroundColor(ContextCompat.getColor(this@MainActivity,R.color.toastBackground))
}
Toast(this).apply {
setGravity(Gravity.TOP,0,0)
view = toastView
duration = Toast.LENGTH_LONG
}.show()
}