什么时候允许将 Context 转换为 Activity?
在警报对话框类的 showAlret(String message, Context ctx)
方法中,我试图在对话框的布局 XML 中获取对 TextView 的引用:
TextView tv = (TextView)((MyActivity)ctx).findViewById(R.id.tv_about);
当然不是在调用 inflate() 之前:
LayoutInflater li = LayoutInflater.from(ctx);
View view = li.inflate(R.layout.aboutdialog, null);
问题问题是此调用将 tv
返回为 null。
由于代码编译时没有任何警告,我假设这是由于将 Context“非法”转换为 MyActivity 造成的。
我遇到过很多情况,其中将 Context 转换为 Activity 是唯一真正有效的方法,那么为什么在这种情况下这不起作用呢?
什么时候将 Context 转换为 Activity 有意义?
这方面有哪些“潜规则”?
In a showAlret(String message, Context ctx)
method of an alert Dialog class, I am trying to get a reference to TextView in the dialog's layout XML:
TextView tv = (TextView)((MyActivity)ctx).findViewById(R.id.tv_about);
Not before calling inflate() of course:
LayoutInflater li = LayoutInflater.from(ctx);
View view = li.inflate(R.layout.aboutdialog, null);
The problem is that this call returns tv
as null.
Since the code compiles without any warnings, I am assuming that this is due to "illegal" casting of Context to MyActivity.
I have encountered quite a few cases in which casting Context to Activity is the only thing that really works, so why doesn't this work in this case?
When does casting Context to Activity make sense?
What are the "unspoken rules" in this regard?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我知道您的 textview 是对话框 xml 的一部分,因此您需要在对话框视图上而不是活动上 findViewById() 。
I understand that your textview is a part of the dialog xml so, you need to findViewById() on the dialogs view instead of the activity.
不,不是,否则你会有例外。
您确定您的 Activity 在您尝试获取 TextView 时已从 xml 加载了它吗?
No it isn't otherwise you would have exception.
Are you sure that your Activity hs loaded the TextView from xml at the moment you try to get it?
我找到了解决方案。我的错误是我在做:
而不是:
I found the solution. My mistake was that I was doing:
Instead of:
另一方面,当它是一个活动时,您可以将上下文转换为一个活动。 Context 是 Activity 的基类。
当您的方法在 Context 对象上不可用时,您应该只需要转换为 Activity。转换只是告诉编译器您确定它是一个 Activity 的一种方法,因此编译器会假设您知道自己在做什么。
On a side not, you can cast the context to an Activity when it is an Activity. Context is a base class for Activity.
You should only have to cast to an Activity when your method is not available on the Context object. Casting is just a way to tell the compiler that you are sure that it is an Activity therfore the compiler will asume you know what you are doing.