Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 2

Introduction

When using Kotlin on Android etc., there are many people who automatically convert from Java with "Convert Java File to Kotlin File". It actually works, but it's a memo to take it one step further and make better use of Kotlin.

2nd time This time, you will learn the dynamic processing of View of Android Activity. Kotlin version: 1.3

Sample code before Kotlin conversion

First, prepare a sample written in Java. The processing is.

MainActivity.java


public class MainActivity extends AppCompatActivity {

    Button buttonA;
    TextView textViewA;

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

        buttonA = (Button) findViewById(R.id.button_A);
        buttonA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("", "buttonA");
            }
        });

        textViewA = (TextView) findViewById(R.id.text_viewA);
        textViewA.setText(R.string.text1);

        TextView textViewB = (TextView) findViewById(R.id.text_viewB);
        textViewB.setText(R.string.text2);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        buttonA.setClickable(false);
        textViewA.setText(R.string.text2);
    }

Sample code after Kotlin conversion

If this is automatically converted and matched to the original shape, it will surely look like this ...

MainActivity.kt


class MainActivity : AppCompatActivity() {

    var buttonA: Button? = null
    var textViewA: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        buttonA = findViewById<View>(R.id.button_A) as Button
        buttonA?.setOnClickListener { Log.d("", "buttonA") }

        textViewA = findViewById<View>(R.id.text_viewA) as TextView
        textViewA?.setText(R.string.text1)

        val textViewB = findViewById<View>(R.id.text_viewB) as TextView
        textViewB.setText(R.string.text2)
    }

    override fun onRestart() {
        super.onRestart()
        buttonA?.isClickable = false
        textViewA?.setText(R.string.text2)
    }
}

What's wrong

For the time being, it can work without problems ... First, you have to unwrap Nullable (buttonA? ....) every time you use a member variable. findViewById as ***** The description is also meaningless.

Think about how to implement

There are two ways

  1. Use "lateinit" as a member variable to determine the type of findViewById

MainActivity.kt


class MainActivity : AppCompatActivity() {

    lateinit var buttonA: Button
    lateinit var textViewA: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        buttonA = findViewById<Button>(R.id.button_A)
        buttonA.setOnClickListener { Log.d("", "buttonA") }

        textViewA = findViewById<TextView>(R.id.text_viewA)
        textViewA.setText(R.string.text1)

        val textViewB = findViewById<TextView>(R.id.text_viewB)
        textViewB.setText(R.string.text2)
    }

    override fun onRestart() {
        super.onRestart()
        buttonA.isClickable = false
        textViewA.setText(R.string.text2)
    }
}
  1. Use "Kotlin Android Extensions" Method 1 is fine, but it can be implemented more simply. That is "Kotlin Android Extensions (official link)"

It is necessary to add classpath to gradle to use

build.gradle


buildscript {
    ext.kotlin_version = '1.3.41'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        //Add the following line
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
    }
}

Now ready Can be implemented without using findViewById

MainActivity.kt


//* Additional import of ↓ is required
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button_A.setOnClickListener { Log.d("", "buttonA") }

        text_viewA.text = getText(R.string.text1)
        
        text_viewB.text = getText(R.string.text2)
    }

    override fun onRestart() {
        super.onRestart()
        button_A.isClickable = false
        text_viewA.text = getText(R.string.text2)
    }
}

Very simple!

Recommended Posts

Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 3
Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 2
Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 1
[Android] Convert Android Java code to Kotlin
Convert all Android apps (Java) to Kotlin
Road to Java Engineer Part1 Introduction & Environment Construction
<java> Read Zip file and convert directly to string
How to convert a file to a byte array in Java
Convert Java Powerpoint to XPS
How to convert Java radix
[Java] Convert ArrayList to array
Road to Java Engineer Part2 What kind of language is Java?
Java to learn with ramen [Part 1]
Road to Java SE 11 Silver acquisition
Kotlin Class to send to Java developers
How to convert erb file to haml
Log output to file in Java
[Java] Convert 1-to-N List to Map
[Android] Convert Map to JSON using GSON in Kotlin and Java
The road from JavaScript to Java
[Java] Convert array to ArrayList * Caution
[Java] How to use the File class
The road to Web service creation (Part 2)
Java SE8 Silver ~ The Road to Pass ~
Convert from java UTC time to JST time
[Java] Convert Object type null to String type
Convert SVG files to PNG files in Java
Kotlin scope functions to send to Java developers
Sample to unzip gz file in Java
Memo for migration from java to kotlin
<Java> Quiz to batch convert file names separated by a specific character string with a part of the file name
Kotlin functions and lambdas to send to Java developers
[Ruby] How to convert CSV file to Yaml (Yml)
Introduce Kotlin to your existing Java Maven Project
Migrate from Java to Server Side Kotlin + Spring-boot
Write to a file using ShiftJIS-Read a file (Kotlin / JVM)
[Java] Convert DB code to code value using enum
Initial settings for rewriting Java projects to Kotlin
How to convert a solidity contract to a Java contract class
A story about trying to operate JAVA File
Getting started with Kotlin to send to Java developers
What I did when I converted java to Kotlin
Convert Java nested beans to aaa.bbb [0] .ccc format
Where Java programmers tend to trip over Kotlin
How to write Java String # getBytes in Kotlin?
What Java inexperienced people did to study Kotlin
[Java] Convert and import file values with OpenCSV
The road to creating a Web service (Part 1)