简体   繁体   中英

How to call Kotlin class from Java class

I need to pass intent from java activity to Kotlin activity:

Java activity ProfileActivity.class:

 Intent selectGameIntent = new Intent(ProfileActivity.this, kotlin.jvm.JvmClassMappingKt.getKotlinClass(CreateNewPollUserActivity.class).getClass());
                startActivity(selectGameIntent);

And this is my Kotlin activity:

class CreateNewPollUserActivity: AppCompatActivity() {

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


        val max = 45
        val min = 10
        val total = max - min}}

When i run it i have an error:

cannot find symbol
import com.myvote.Profile.ToolbarOption.CreateNewPollUserActivity;

any ideas how send intent from java activity to Kotlin activity?

This is the way to use call Kotlin class from Java class

 Intent selectGameIntent = new Intent(ProfileActivity.this, 
 CreateNewPollUserActivity.class);
  startActivity(selectGameIntent);

In your code, Probably the problem lays not in the Java-Kotlin relation, but in something else. Please check your code/project.

add this in build.gradle project

buildscript {
    ext.kotlin_version = '1.5.21'
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

And on top of build.gradle module file

apply plugin: 'kotlin-android'

For this aim, you need to do several steps:

1- build.gradle project

classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10'

2- build.gradle app

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

3- Introduction the class and fun:

kotlin kt:

class CountTime(val activity: Activity) {
fun seeNext(t: String, c: String, ico: Int, i: Int) {

java MainActivity

CountTime countTime = new CountTime(this);
countTime.seeNext(t,c,ico,i);

and if there is a companion object

.Companion.getInstance();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM