什么是“活动?”。在Kotlin中的意思?
我正在尝试使用官方Android文档中的代码段( https> https:htttps:// devagenter。 android.com/training/printing/photos#kotlin )是dophotoprint()函数在我附加的代码中,以学习如何在Kotlin和Android Studio中使用打印机类。请参阅代码段的随附图像:
问题是当我将代码放入我的测试应用程序中的主要活动不断显示“活动?”。像红色。为什么这种情况?如何使代码工作以便为用户提供打印的选项?谢谢
I am trying to use a code snippet from the official android documentation (https://developer.android.com/training/printing/photos#kotlin) which is the doPhotoPrint() function in the code that I have attached, in order to learn how to use the PrintHelper class in Kotlin and Android Studio. See the attached image of the the code snippet:
The problem is that when I put the code in Main Activity in my test app, it keeps showing "activity?." as red. Why is this the case and how can I get the code to work so that is provides the user with the option to print? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您链接的代码只是一般如何使用库函数代码 shippet-均未在任何上下文中放置,但是我们可以假设它可能是用
fragment
编写的。片段具有agetActivity(getAccevity> getActivity()
返回活动
的方法当前已连接到(或 null (如果不是))Kotlin允许您从Java代码 > - 基本上,而不是必须做
value = getthing()
setthing(newValue)
您可以将其视为变量:value = thing
,thing = newValue
等。 >活动属性在此代码中,它确实在调用getActivity()
。而且,由于结果可能为null,因此您在尝试对其进行任何操作之前,请使用?
对其进行null检查。该代码的说法确实是,该代码需要访问
上下文
,并且使用活动
作为示例中的一个。如果您有一个fragment
,则可以直接删除此代码。如果您在activity
中一个 -这个
是您的活动!当然,您无需取消检查它。 (并且没有活动
属性或getActivity()
访问方法,这就是为什么它显示出红色和未被认可的原因),因此您可以替换这些东西和周围的检查代码它与:
The code you linked is just a general how to use a library function snippet - it's not put in any context, but we can assume it's probably written with a
Fragment
in mind. Fragments have agetActivity()
method that returns theActivity
it's currently attached to (or null if it's not)Kotlin allows you to access getter and setter functions from Java code as if they were properties - so basically, instead of having to do
value = getThing()
and
setThing(newValue)
you can treat it like a variable:value = thing
,thing = newValue
etc. So when you access theactivity
property in this code, it's really callinggetActivity()
. And because the result can be null, you use the?
to null-check it before trying to do anything with it.Really what that snippet is saying is, this code needs access to a
Context
, and it's using anActivity
as one in the example. If you have aFragment
, you can just drop this code right in. If you're in anActivity
though, then you obviously don't need to get one -this
is your Activity! And you don't need to null-check it either of course. (And there's noactivity
property orgetActivity()
method to access, which is why it's showing up red and unrecognised)So you can just replace that stuff and the checking code around it with:
它显示红色,因为您在使用之前尚未声明无效的对象活动
It is showing red because you have not declared the nullable object activity anyway before you use it