Search code examples
androidkotlinanko

Can't Call StartActivityForResult in Anko


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?


Solution

  • startActivityForResult can only be called on an Activity because only an Activity can receive a result from another finishing Activity. There are a few solutions, probably the easiest would be to change your custom ViewGroup so that it accepts an Activity instead of just a Context, or, if you know you will only use that ViewGroup from an Activity, just cast the Context to an Activity.

    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. The ViewGroup could for example allow listeners to register for the event that right now triggers the navigation action. This way, the Activity can register for that event, do the navigation itself and handle the result outside of the ViewGroup.