自定义视图如何访问其活动?
我有一个自定义视图,想要访问其活动中可用的字符串。我见过在视图类中使用 getContext()
的代码,但是没有方法可以访问通过 Intent 对其活动可用的 String。如何使活动中的字符串可用于其自定义视图?
I have a custom view and would like to access a String that is available in its activity. I've seen code that uses getContext()
in the view class, but there is no method to access the String that has been made available to its activity via an intent. How to make a String in an activity available to its custom view?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
View 类中的 getContext() 方法返回传递给其构造函数的上下文。通常这就是您想要的活动(活动扩展了上下文)。
所以这可能适合你:
Java:
Kotlin:
The getContext() method in the View class returns the context that was passed on its constructor. Usually that's the Activity you want (Activity extends Context).
So this probably works for you:
Java:
Kotlin:
我仍然是 java 和 android 的菜鸟,所以这可能不起作用,但我只是想提供帮助。
您应该能够使用“putExtra”和“getExtra”将参数传递给意图/活动,例如:
在您的主要活动中:
然后在新视图中的“onCreate”方法中,使用以下内容:
显然我已经使用了我自己的代码在这里,但当用户单击按钮时,我将行信息传递到新活动中。
有关使用 putextra 和 getextra 的更多信息,请参阅此链接:使用 Intent.putExtra 发送数组
希望这有帮助,这是我对社区的第一个贡献:)
I'm a noob to java and android still, so this may not work, but I'm just trying to help.
You should be able to pass in parameters to intents/activities using "putExtra" and "getExtra", for example:
In your main activity:
Then in the "onCreate" method in your new view, use the following:
obviously I've used my own code here, but I am passing row information into a new activity when a user clicks a button.
See this SO link for more info on using putextra and getextra: Sending arrays with Intent.putExtra
Hope this helps, it's my first contribution back to the community :)