이번 편에서는 레이아웃과 코틀린 코드사이의 연결에 대해서 알아보겠습니다. 레이아웃에 만들어둔 도구(컴포넌트)에 동작을 입히는 과정입니다.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="start|top"
android:inputType="textMultiLine"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintTop_toBottomOf="@+id/editText"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintTop_toBottomOf="@+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
위와 같이 3개의 컴포넌트들을 생성해두었었지요. EditText, Button, TextView 각각의 id 는 "editText", "button", "textView"입니다.
번역기를 개발해보겠다고 하였었지요? EditText에는 번역하고자 하는 단어(예: LOVE)를 적을 것이고, Button 을 누르면 번역작업을 거쳐 TextView 에 변역된 결과(예: 사랑)가 보여지도록 할 예정입니다. 다만 번역하는 부분은 구글의 API 를 사용해야해서 다음 편에서 진행해보도록 하겠습니다.
1. button 에 대해서 동작을 정의하고 싶으면 아래와 같이 해주면 됩니다.
그런데 button이 빨간색으로 표시되네요. 에러가 있다는 것인데요. 마우스를 가져다대면 아래와 같은 설명이 표시됩니다. MainActivity.kt 코드에서는 button 이라는 것이 어디서 왔는지 알지 못합니다. 그래서 button이 무엇인지 어디서 왔는지 알려줄 필요가 있습니다. 그게 바로 Import 입니다. 파란 "Import"버튼을 눌러도 되고, Mac 단축키(ALT + SHIFT + ENTER) 를 입력해줘도 됩니다.
아래와 같이 한줄이 추가되었습니다. activity_main.xml 레이아웃 파일내의 모든(*) 컴포넌트들을 import 하겠다는 것입니다. 이제 button 코드부분의 빨간색이 사라졌네요.
그러면 button 이 눌렸을 때, EditText의 내용을 TextView에 작성되도록 해볼까요? 아래와 같이 작성하면 됩니다. 간단하지 않습니까. 저도 Java로 개발하다 Kotlin 접하니 이렇게 간결할수가 없습니다.
Java로 개발하였다고 하면 아래와 같이 작성해주었어야 했을텐데, 확연하게 짧은 것을 알 수 있습니다. Kotlin 인정!
EditText edit = findViewById(R.id.editText);
Button btn = findViewById(R.id.button);
TextView text = findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
text.setText(edit.getText());
}
});
그러면 그 결과를 확인해보도록 하겠습니다. Button을 눌렀을 때, EditText의 내용이 TextView 에 잘 표시되는 것을 확인할 수 있었습니다.
다음편에서는 구글 번역 API를 이용해서 번역된 결과를 TextView에 적어보도록 하겠습니다.
감사합니다.
'Programming > Android' 카테고리의 다른 글
Mac 안드로이드 앱개발(5) - 안드로이드 프로젝트 구성 (0) | 2020.05.06 |
---|---|
Mac 안드로이드 앱개발(4) - 안드로이드 기기에서 앱 실행 (0) | 2020.05.06 |
Mac 안드로이드 앱개발(3) - Android Studio 애뮬레이터 실행 (0) | 2020.05.05 |
Mac 안드로이드 앱개발(2) - Android Studio 프로젝트 만들기 (0) | 2020.05.04 |
Mac 안드로이드 앱개발(1) - Android Studio 설치 (0) | 2020.05.04 |