Activity에 hello world 출력하기
코틀린으로 안드로이드 개발을 시작해보려고 합니다. 첫걸음으로 Hello World와 Hello Kotlin을 출력하고 버튼을 하나 추가하여 두 문장을 교대로 변경하도록 해보았습니다.
기억이 가물가물하여 대충 생각하는 코틀린 문법들을 이용해서 작성해봤습니다. 다시 코틀린 문법을 되새기면서 안드로이드에 어떻게 적용되는지 살펴보도록 하겠습니다.
1차 목표는 예전에 Android Programming: The Big Nerd Ranch Guide(2nd ed.) 를 공부하면서 접한 예제를 응용하여 학습용으로 만들어두었던 국가 수도 맞추기 앱을 코틀린으로 포팅하는 것입니다.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.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="kotlinapp.circus.com.kotlinapplication.MainActivity">
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical">
<TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"/>
<TextView android:id="@+id/tv2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"/>
<Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Change Sentence"/> </LinearLayout> </android.support.constraint.ConstraintLayout>
|
MainActivity.java
package kotlinapp.circus.com.kotlinapplication import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.TextView import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main)
var tv = findViewById(R.id.tv) as TextView tv.setText("Hello Kotlin")
tv2.setText("Hello World")
var button:Button = findViewById(R.id.button) button.setOnClickListener(View.OnClickListener { var temp:String? = null temp = tv.text.toString() tv.setText(tv2.text) tv2.setText(temp) }) } }
|


국가 수도 맞추기 앱 간단 소개
이전, 다음으로 이동할 때마다 선택지 위치 및 오답 종류가 변경됩니다.
정답을 선택하면 정답! 틀리면 오답! 토스트를 띄웁니다.

