Kotlin to Java?

So far, we've gone through the process of creating a Kotlin class and accessing its method in our MainActivity.java class. Our project currently consists of a Java class and a Kotlin class, but we want our entire project to be in Kotlin. So, what do we do? Do we have to rewrite the MainActivity.java class in Kotlin? No. One of the functionalities the Kotlin plugin adds to Android Studio is the ability to convert code from Java to Kotlin.

To do this, open the MainActivity.java class and go to Code | Convert Java File to Kotlin File:

                                                         

You will be prompted with a warning message about the accuracy of the conversion. For now, we don't need to worry about that. Just click OK to continue:

                                   

YourMainActivity.javaclass should now look like this:

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)

val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener { view ->
HelloKotlin().displayKotlinMessage(view) }
}

override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is
//present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId


return if (id == R.id.action_settings) {
true
} else super.onOptionsItemSelected(item)

}
}

You will also notice that the extension of the file has also changed to .kt.

Once again, build and run your app:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset