SetOnClickListener을 통해 Button의 동작을 설정할 수 있다.
- Log.d -> log에 동작의 디버깅을 기록한다. logcat을 통한 디버깅을 통해서 어떤 오류가 발생했는지 파악이 가능하다. ex)Log.d("MainActivity", "ResultButton 이 클릭되었습니다.")
- intent -> 화면전환의 역할.
- intent가 실제로 동작하기위해서 현재 엑티비티와 전환할 엑티비티를 명시해줘야한다.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val heightEditText:EditText = findViewById(R.id.heightEditText)
val weightEditText = findViewById<EditText>(R.id.weightEditText)
val resultButton: Button = findViewById(R.id.resultButton)
resultButton.setOnClickListener{
if(heightEditText.text.isEmpty() || weightEditText.text.isEmpty()){
Toast.makeText(this, "빈 값을 채워주세요.", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
//return 문으로 실행을 종료. 이후의 연산이 실행되지 않음.
//값을 넣지 않으면 실행이 되지 않음.
val height:Int = heightEditText.text.toString().toInt()
val weight:Int = weightEditText.text.toString().toInt()
//height와 weight를 Int형으로 선언하기위해서 text를 문자열로, 문자열에서 Int로 변환해줌.
val intent = Intent(this, ResultActivity::class.java)
startActivity(intent)
}
}
새로운 화면을 패키지에 추가하면 항상 manifest에 새로운 activity를 생성했음을 명시해줘야한다.