일정 시간이 지나면 자동으로 사라지는 메세지
화면과 관련 없이 안드로이드 OS에 메세지 출력 요청 후 안드로이드 OS에 의해 나타나는 메세지 (어플리케이션과의 관계 X)
val t1 = Toast.makeText(this@MainActivity,"toast message",Toast.LENGTH_SHORT)
t1.show()
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
t1.addCallback(object:Toast.Callback(){
override fun onToastShown() {
super.onToastShown()
}
override fun onToastHidden() {
super.onToastHidden()
}
})
}
val toastBinding = ToastBinding.inflate(layoutInflater)
toastBinding.run {
val t1 = Toast(this@MainActivity)
}
toastBinding.root.setBackgroundResource(android.R.drawable.screen_background_dark)
textView.setTextColor(Color.WHITE)
t1.setGravity(Gravity.CENTER,0,200)
t1.view = toastBinding.root
t1.duration = Toast.LENGTH_LONG
activity 위에 표시되며 하단에 나타나는 메세지
snackBar1 = Snackbar.make(it, "snackBar message", Snackbar.LENGTH_INDEFINITE)
snackBar1.show()
// snackBar1 변수가 초기화 되어있는 경우
if(::snackBar1.isInitialized){
// 보여지고 있는 경우
if(snackBar1.isShown){
snackBar1.dismiss()
}
}
snackBar1.addCallback(object : BaseTransientBottomBar.BaseCallback<Snackbar>(){
override fun onShown(transientBottomBar: Snackbar?) {
super.onShown(transientBottomBar)
}
override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
super.onDismissed(transientBottomBar, event)
}
})
snackBar1.setTextColor(Color.RED)
snackBar1.setBackgroundTint(Color.BLUE)
snackBar1.animationMode = Snackbar.ANIMATION_MODE_SLIDE
snackBar1.setAction("Action1"){
activityMainBinding.textView.text = "action1 click"
}
val snackBar1 = Snackbar.make(it, "Custom SnackBar", Snackbar.LENGTH_SHORT)
val snackbarBinding = SnackbarBinding.inflate(layoutInflater)
snackbarBinding.run{
imageView.setImageResource(R.drawable.img_android)
textView.text = "View"
textView.setTextColor(Color.WHITE)
}
val snackBarLayout = snackBar1.view as Snackbar.SnackbarLayout
snackBarLayout.addView(snackbarBinding.root)
activity 위에 나타나는 메세지
메세지 전달이나 입력 등의 용도로 사용하는 메세지
val builder = AlertDialog.Builder(this@MainActivity)
builder.show()
builder.setTitle("Dialog")
builder.setMessage("message")
builder.setIcon(R.mipmap.ic_launcher)
builder.setPositiveButton("Positive", null)
builder.setPositiveButton("Positive"){ dialogInterface: DialogInterface, i: Int ->
textView.text = "Positive button click"
}
val dialogBinding = DialogBinding.inflate(layoutInflater)
val builder = AlertDialog.Builder(this@MainActivity)
builder.setView(dialogBinding.root)
builder.setPositiveButton("확인", ) { dialogInterface: DialogInterface, i: Int -> }
builder.setNegativeButton("취소", null)
날짜를 선택할 수 있게 하기 위해 사용하는 dialog
val calendar = Calendar.getInstance()
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)
val datePickerListener = object : DatePickerDialog.OnDateSetListener{
override fun onDateSet(p0: DatePicker?, p1: Int, p2: Int, p3: Int) {
textView.text = "${p1}년 ${p2+1}월 ${p3}일"
}
}
val pickerDialog = DatePickerDialog(this@MainActivity, datePickerListener, year, month, day)
pickerDialog.show()
시간을 선택할 수 있게 하기 위해 사용하는 dialog
val calendar = Calendar.getInstance()
val hour = calendar.get(Calendar.HOUR)
val minute = calendar.get(Calendar.MINUTE)
val timePickerListener = object : TimePickerDialog.OnTimeSetListener{
override fun onTimeSet(p0: TimePicker?, p1: Int, p2: Int) {
textView.text = "${p1}시 ${p2}분"
}
}
val pickerDialog = TimePickerDialog(this@MainActivity, timePickerListener, hour, minute, true)
pickerDialog.show()
listView를 표시할 수 있는 dialog
val dataList = arrayOf(
"항목1", "항목2", "항목3", "항목4", "항목5", "항목6",
"항목7", "항목8", "항목9", "항목10", "항목11", "항목12",
"항목13", "항목14", "항목15", "항목16", "항목17", "항목18"
)
val adapter = ArrayAdapter<String>(
this@MainActivity, android.R.layout.simple_list_item_1, dataList
)
val builder = AlertDialog.Builder(this@MainActivity)
builder.setAdapter(adapter){ dialogInterface: DialogInterface, i: Int ->
textView.text = "${dataList[i]}"
}
builder.setNegativeButton("취소", null)
체크박스 형태를 제공하는 dialog
val dataList = arrayOf(
"항목1", "항목2", "항목3", "항목4", "항목5", "항목6",
"항목7", "항목8", "항목9", "항목10", "항목11", "항목12",
"항목13", "항목14", "항목15", "항목16", "항목17", "항목18"
)
// 모두 false로 설정
val mutilChoiceList = BooleanArray(dataList.size){i -> false}
val builder = AlertDialog.Builder(this@MainActivity)
builder.setMultiChoiceItems(dataList, mutilChoiceList){ dialogInterface: DialogInterface, i: Int, b: Boolean ->
mutilChoiceList[i] = b
}
builder.setNegativeButton("취소", null)
builder.setPositiveButton("확인", ){ dialogInterface: DialogInterface, i: Int ->
textView.text = ""
for(idx in 0 until mutilChoiceList.size){
if(mutilChoiceList[idx] == true){
textView.append("${dataList[idx]}\n")
}
}
}
알림창에 표시되는 메세지
안드로이드 버전 13 이후 : notification 사용시 POST_NOTIFICATIONS 권한을 사용자로부터 확인 받는다.
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
val permissionList = arrayOf(
Manifest.permission.POST_NOTIFICATIONS
)
requestPermissions(permissionList, 0)
fun addNotificationChannel(id:String, name:String){
// 안드로이드 8.0 이상일 때만 동작
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
// 알림 메시지를 관리하는 객체 추출
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
// id를 통해 NotificationChannel 객체 추출
// 채널이 등록된 적이 없는 경우 : null 반환
val channel = notificationManager.getNotificationChannel(id)
// 채널이 등록된 적이 없는 경우
if(channel == null){
// 채널 객체 생성
val newChannel = NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH)
// 단말기에 LED 램프가 있다면 램프를 사용하도록 설정
newChannel.enableLights(true)
// LED 램프의 색상 설정
newChannel.lightColor = Color.RED
// 진동 사용 설정
newChannel.enableVibration(true)
// 채널 등록
notificationManager.createNotificationChannel(newChannel)
}
}
}
// Notification Channel을 코드에서 구분하기 위한 이름 설정
val NOTIFICATION_CHANNEL1_ID = "CHANNEL1"
val NOTIFICATION_CHANNEL2_ID = "CHANNEL2"
// 사용자게 노출 시킬 채널의 이름 설정
val NOTIFICATION_CHANNEL1_NAME = "첫 번째 채널"
val NOTIFICATION_CHANNEL2_NAME = "두 번째 채널"
addNotificationChannel(NOTIFICATION_CHANNEL1_ID, NOTIFICATION_CHANNEL1_NAME)
addNotificationChannel(NOTIFICATION_CHANNEL2_ID, NOTIFICATION_CHANNEL2_NAME)
fun getNotificationBuilder(id:String) : NotificationCompat.Builder{
// 안드로이드 8.0 이상일 때만 동작
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val builder = NotificationCompat.Builder(this, id)
return builder
} else {
val builder = NotificationCompat.Builder(this)
return builder
}
}
val builder = getNoficationBuilder(NOTIFICATION_CHANNEL1_ID)
val notification = builder.build()
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(10, notification)
builder.setSmallIcon(android.R.drawable.ic_menu_search)
val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
builder.setLargeIcon(bitmap)
builder.setNumber(100)
builder.setContentTitle("Content Title")
builder.setContentText("Content Text")
addNotificationChannel(NOTIFICATION_CHANNEL1_ID, NOTIFICATION_CHANNEL1_NAME)
addNotificationChannel(NOTIFICATION_CHANNEL2_ID, NOTIFICATION_CHANNEL2_NAME)
activityMainBinding.run{
button.setOnClickListener {
val builder = getNoficationBuilder(NOTIFICATION_CHANNEL1_ID)
builder.setSmallIcon(android.R.drawable.ic_menu_search)
val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
builder.setLargeIcon(bitmap)
builder.setNumber(100)
builder.setContentTitle("Content Title")
builder.setContentText("Content Text")
val notification = builder.build()
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(10, notification)
}
}
fun addNotificationChannel(id:String, name:String){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
val channel = notificationManager.getNotificationChannel(id)
if(channel == null){
val newChannel = NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH)
newChannel.enableLights(true)
newChannel.lightColor = Color.RED
newChannel.enableVibration(true)
notificationManager.createNotificationChannel(newChannel)
}
}
}
fun getNoficationBuilder(id:String) : NotificationCompat.Builder{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val builder = NotificationCompat.Builder(this, id)
return builder
}
else {
val builder = NotificationCompat.Builder(this)
return builder
}
}