Android

Android - Java 프로젝트에서 Kotlin 사용하기

꿈다루 2021. 9. 8. 17:59

1. Java Project 생성

 * Language => Java 선택 *

 

2. Android Studio -> Preferences -> Plugins -> "Kotlin" 검색  -> Install

 

 

3. build.gradle(Project) / build.gradle(Module)

 

 

- build.gradle(Project)

 

- build.gradle(Module)

 

4. Code 

 

- activity_main.xml

<?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">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hi"
        android:textAppearance="?android:attr/textAppearanceMedium"
        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="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/text"
        />
</androidx.constraintlayout.widget.ConstraintLayout>

 

- MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView tvText;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvText = (TextView) findViewById(R.id.text);
        btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.button) {
            tvText.setText(HelloKt.formatMessage("Android with kotlin"));
        }
    }
}

 

- Hello.kt

fun formatMessage(name: String): String = "Hello, $name"

 

5. 실행화면