I'm pretty new to android, and I'm trying to learn it with kotlin. In this code
mHelp.setOnClickListener {context.startActivity<HelpActivity>()}
mSettings.setOnClickListener {
context.startActivityForResult<LocalSettingsActivity>(
LOCAL_SETTINGS_REQUEST,
"coords" to this.board.mCoords,
"drag" to this.mWhiteStones[0].drag )
}
the call to startActivity
works fine, but I get a syntax error on the call to startActivityForResult
. The error says that it's a receiver type mismatch, and that the receiver should be an Activity
or a Fragment
. On the other hand, the receiver for StartActivity
can be a Fragment
, a Context
, or an AnkoContext<*>
(whatever that is).
Of course, I can make this work (I think) by building the Intent
and not using anko.StartActivityForResult
, but I'd to understand what's going on.
It has occurred to me that perhaps I've got my code organized all wrong. The code above is in a custom ViewGroup
that has the ImageButtons
mHelp and mSettings as children, and context
is the Context
passed to the ViewGroup
's primary constructor. Should I perhaps be setting the onClickListeners
in the Activity
that manages the custom ViewGroup
? If not, how would I call StartActivityForResult
?
startActivityForResult
can only be called on anActivity
because only anActivity
can receive a result from another finishingActivity
. There are a few solutions, probably the easiest would be to change your customViewGroup
so that it accepts anActivity
instead of just aContext
, or, if you know you will only use thatViewGroup
from anActivity
, just cast theContext
to anActivity
.You are right though when you say that your code could probably be organized better, to circumvent this problem altogether. Just following separation of concerns, your
ViewGroup
should not be responsible for navigation actions in your App. TheViewGroup
could for example allow listeners to register for the event that right now triggers the navigation action. This way, theActivity
can register for that event, do the navigation itself and handle the result outside of theViewGroup
.