리스너 이벤트 처리 실습

tpids·2024년 8월 13일

Android

목록 보기
11/29

MainActivity2.kt

package com.example.ex_event

import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.ex_event.databinding.ActivityMain2Binding

// class MainActivity2 : AppCompatActivity(), View.OnClickListener {
class MainActivity2 : AppCompatActivity() {
    lateinit var binding : ActivityMain2Binding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMain2Binding.inflate(layoutInflater)
        setContentView(binding.root)

        // OnClick() 호출하기 -> 리스너를 통하여 this 키워드 호출
//        binding.btnR.setOnClickListener(this)
//        binding.btnG.setOnClickListener(this)
//        binding.btnB.setOnClickListener(this)
        
        // Event3) 익명의 클래스를 통하여 간단하게 이벤트를 연결하는 방법
        binding.btnR.setOnClickListener() {
            // 리스너가 연결되었을 때 처리하고자 하는 이벤트 로직 작성
            binding.layout.setBackgroundColor(Color.RED)
        }
        binding.btnG.setOnClickListener() {
            // 리스너가 연결되었을 때 처리하고자 하는 이벤트 로직 작성
            binding.layout.setBackgroundColor(Color.GREEN)
        }
        binding.btnB.setOnClickListener() {
            // 리스너가 연결되었을 때 처리하고자 하는 이벤트 로직 작성
            binding.layout.setBackgroundColor(Color.BLUE)
        }

    }

//    override fun onClick(v: View?) {
//        // 버튼이 감지되었을 때 3개의 버튼 중 어떤 버튼이 감지되었는지 판단
//        if (v?.id == binding.btnR.id) {
//            // ?.id -> 실제 클릭된 버튼의 id값을 담아오는 기능
//            binding.layout.setBackgroundColor(Color.RED)
//        } else if (v?.id == binding.btnG.id) {
//            // ?.id -> 실제 클릭된 버튼의 id값을 담아오는 기능
//            binding.layout.setBackgroundColor(Color.GREEN)
//        } else if (v?.id == binding.btnB.id) {
//            // ?.id -> 실제 클릭된 버튼의 id값을 담아오는 기능
//            binding.layout.setBackgroundColor(Color.BLUE)
//        }
//    }
}

profile
개발자

0개의 댓글