Fagments and Activities

What is the proper way to make an intent to an new Activity using the setOnclickListener method? (Because I know they always make new ways to do the same thing)
I know we can call the id of the button ex. if the buttons id was helloButtonId we would explicitly call it like:

helloButtonId.setOnclickListener{

val newPage = Intent(this,Main2Activity::class.java)

startActivity(newPage)

}

My App always forecloses when I putt code in the setOnclickListener?
Can some smart nice person please post some simple code of an OnlickListner starting a new Acitvity so I can see what I’m doing wrong?

Here are the versions and my dependencies I have in my project:

//versions

minSdkVersion 27

targetSdkVersion 28

//dependecies

implementation fileTree( dir : ‘libs’ , include : [ ‘*.jar’ ])

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7: $kotlin_version "

implementation ‘com.android.support:appcompat-v7:28.0.0’

implementation ‘com.android.support.constraint:constraint-layout:1.1.3’

implementation ‘com.android.support:support-v4:28.0.0’

testImplementation ‘junit:junit:4.12’

androidTestImplementation ‘com.android.support.test:runner:1.0.2’

androidTestImplementation ‘com.android.support.test.espresso:espresso-core:3.0.2’

I needed to make an interface in my first fragment and make an abstarct fun in the interface.

Then I had to make my main.kt implement my interface then override the function in the interface.in main.kt

Then use onclick in the views attribute and equal it to the name of the abstarct fun so when the view is click it will call that fun in main where you overid

That kind of thing should only be necessary if you wish to communicate something from the fragment to the containing activity. Did you create the fragment from a File->New->Fragment template?

Yeah I created the first fragment was inflated then I replaced it it with another fragment. I spent so long trying to do this simple function but o finally made it work in the simplest way but it still worked .lol

If the application force closes. It could be because not registering your Activity in the Manifest file.
Also to start an activity I use anko
startActivity()

I think (based on the description given) what happened is that @rickster21 created a new fragment with the “Include interface callbacks?” option checked. Trying to load that fragment into an activity that does not implement the generated interface causes a crash (RuntimeException thrown in onAttach).

@rickster21, Anko is pretty cool (I hope it gets updated soon to be in line with Kotlin 1.3.x)

It allows calls like this:
startActivity<Main2Activity>()

or, when passing arguments:

startActivity<Main2Activity>(Main2Activity.MY_ARG to value)

Where to is just a convenient way to express a Pair<A, B>