와챠의 우당탕탕 코딩 일기장

[안드로이드] 7장 연습문제 5번(랜덤 위치에 토스트 띄우기) 본문

코딩 일기장/Android(Kotlin)

[안드로이드] 7장 연습문제 5번(랜덤 위치에 토스트 띄우기)

minWachya 2021. 4. 10. 19:51
반응형

5번

버튼을 클릭하면 임의의 위치에 이미지가 들어간 토스트가 나오는 프로젝트를 작성하시오.

결과 화면

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:gravity="center">
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="토스트 보이기"
android:textSize="20dp"
android:backgroundTint="#cccccc"
android:textColor="#000000"/>
</LinearLayout>

 

toast.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imgDog"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/dog" />
</LinearLayout>
view raw toast.xml hosted with ❤ by GitHub

 

MainActivity.kt

package com.example.mytest
import android.content.Context
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var btn : Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "7장 연습문제 5번"
btn = findViewById<Button>(R.id.btn)
btn.setOnClickListener {
// 토스트 만들기
var toast = Toast(this@MainActivity)
// 토스트에 들어갈 뷰 만들기, 이때 연결될 뷰 설정
var toastView = View.inflate(this@MainActivity, R.layout.toast, null)
// 토스트 뷰 연결
toast.view = toastView
// 토스트 랜덤 위치에 출력하기
var display = (getSystemService(Context.WINDOW_SERVICE) as
WindowManager).defaultDisplay
var xOffset = (Math.random() * display.width).toInt()
var yOffset = (Math.random() * display.height).toInt()
toast.setGravity(Gravity.TOP or Gravity.LEFT, xOffset, yOffset)
// 토스트 보이기
toast.show()
}
}
}
view raw MainActivity.kt hosted with ❤ by GitHub

강아지 사진으로 하니까 진짜 강아지가 여기저기 뛰노는 거 같아서 넘 귀여웠다.

 

반응형
Comments