如何从视图中获取托管活动?
我有一个带有 3 个 EditText 的 Activity
和一个自定义视图,该视图充当专用键盘以将信息添加到 EditText
中。
目前,我正在将 Activity
传递到视图中,以便我可以获得当前聚焦的编辑文本并从自定义键盘更新内容。
有没有一种方法可以引用父活动并获取当前聚焦的 EditText
而不将活动传递到视图中?
I have an Activity
with 3 EditText
s and a custom view which acts a specialised keyboard to add information into the EditText
s.
Currently I'm passing the Activity
into the view so that I can get the currently focused edit text and update the contents from the custom keyboard.
Is there a way of referencing the parent activity and getting the currently focused EditText
without passing the activity into the view?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
我刚刚从 官方支持库 到目前为止,它工作正常:
I just pulled that source code from the MediaRouter in the official support library and so far it works fine:
以下方法可能会帮助您
Activity host = (Activity) view.getContext()
;和view.isFocused()
在使用它之前,您至少应该首先检查它是否是一个 Activity:
following methods may help you
Activity host = (Activity) view.getContext()
; andview.isFocused()
You should first check if it is an Activity at minimum before using it:
已更新
感谢@Westy92
用法:
UPDATED
thanks to @Westy92
Usage:
我采用了 Gomino 的 答案 并将其修改为完全适合 myUtils.java,这样我就可以随时随地使用它。希望有人觉得它有帮助:)
I took Gomino's answer and modified it to fit perfectly in myUtils.java so I can use it wherever and whenever I need. Hope someone finds it helpful :)
只是想注意,如果您知道您的视图位于
Fragment
内,您可以这样做:从
onAttachedToWindow
或onDraw
调用此方法,您不能提前调用它(例如onFinishInflate
),否则您将收到异常。如果您不确定您的视图是否在
Fragment
内,请参考其他答案,例如 Gomino,只是想将其扔在那里。Just want to note that, if you know that your view is inside a
Fragment
, you can just do:Call this from your
onAttachedToWindow
oronDraw
, you can't call it earlier (e.g.onFinishInflate
) or you will get an exception.If you are not sure your view is inside a
Fragment
then refer to other answers e.g. Gomino, just wanted to throw it out there.基于 @gomino 的 Kotlin 答案
Kotlin answer based on @gomino
View 的 Kotlin 扩展属性用于检索父活动:
Kotlin extension property for View to retrieve parent activity:
在 Android 7+ 中,视图无法再访问封闭的 Activity,因此无法再将
view.getContext()
转换为 Activity。相反,下面的代码适用于 Android 7+ 和 6:
In Android 7+ the view does not have access to the enclosing activity anymore, so
view.getContext()
can't be cast to an Activity anymore.Instead, the code below works in Android 7+ and 6:
@覆盖
公共布尔shouldOverrideUrlLoading(WebView视图,WebResourceRequest请求){
if(request.getUrl().getHost().startsWith("pay.google.com")) {
Intent意图 = new Intent(Intent.ACTION_VIEW, request.getUrl());
view.getContext().startActivity(意图);
返回真;
}
...
...
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if(request.getUrl().getHost().startsWith("pay.google.com")) {
Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
view.getContext().startActivity(intent);
return true;
}
...
...
}