Issue
I was trying create a Button that makes the user to a new Activity, i create something like that:
//Main Activity
btnChangeScene.setOnClickListener { goToActivity(this, SecondActivity::class.java) }
fun Context.goToActivity(activity: Activity, classs: Class<*>?) {
val intent = Intent(activity, classs)
startActivity(intent)
activity.finish()
}
But when I try to go back to MainActivity, I need to create a new "goToActivity" inside SecondActivity and that's so bad for any programmer, because for every new activity, I need to create a new "goToActivity" inside it.
How can I get this same function implemented inside this class, so I can just call this function, instead of having to create it every time I create a new activity?
class ButtonActivity(private val button: Button): Activity(){
// code here
}
Solution
create a new kotlin companion object like below.
companion object AnyName {
fun Context.goToActivity(activity: Activity, classs: Class<*>?) {
val intent = Intent(activity, classs)
startActivity(intent)
activity.finish()
}
}
now you call this function from any class.
Answered By - vignesh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.