Can't Call StartActivityForResult in Anko

£可爱£侵袭症+ 提交于 2019-12-11 03:35:47

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/45225642/cant-call-startactivityforresult-in-anko

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!