使用 Kotlin 在 android 中的 UI 组件上声明的最佳方法是什么? [英] What is the best way to declare on UI component in android with Kotlin?

查看:28
本文介绍了使用 Kotlin 在 android 中的 UI 组件上声明的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次尝试使用 Kotlin 构建 android 应用程序.

I'm trying to build android application using Kotlin for the first time.

我想在 OnCreate 方法之外的一些按钮上声明,我只能在这个函数内部使用 findViewById 初始化它们.

I want to declare on some buttons outside the OnCreate method and i can initialize them only Inside this function with findViewById.

我可以像在 Java 中一样用简单干净的代码声明吗?

Can i declare in simple and clean code like in java?

private Button btnProceed;

因为当将其转换为 Kotlin 时,它看起来像:

Because when converting it to Kotlin it look like:

private var btnProceed: Button? = null

然后在初始化 OnClick 函数时需要添加!签名:

And then when initialize OnClick function need to add ! sign:

btnProceed!!.setOnClickListener

什么是正确和最干净的方法?

What is the right and cleanest way?

推荐答案

这是 lateinit.标记属性 lateinit 允许您使其不可为空,但不能在调用 Activity 的构造函数时为其分配值.当初始化发生在一个单独的初始化方法中,比构造函数运行晚(在这种情况下,onCreate)时,它正好适用于像活动这样的类.

This is a good use case for lateinit. Marking a property lateinit allows you to make it non nullable, but not assign it a value at the time that your Activity's constructor is called. It's there precisely for classes like Activities, when initialization happens in a separate initializer method, later than the constructor being run (in this case, onCreate).

private lateinit var btnProceed: Button

如果在给它分配实际值之前读取该属性,它将在运行时抛出异常 - 通过使用 lateinit,您负责在访问它之前对其进行初始化第一次.

If the property is read before a real value is assigned to it, it will throw an exception at runtime - by using lateinit, you're taking the responsibility for initializing it before you access it for the first time.

否则,如果您希望编译器为您保证安全访问,您可以将 Button 设为可空,就像转换器默认情况下所做的那样.而不是不安全的 !! 运算符 但是,转换器经常使用,您应该使用 安全调用运算符 访问属性的位置:

Otherwise, if you want the compiler to guarantee safe access for you, you can make the Button nullable as the converter does by default. Instead of the unsafe !! operator though, which the converter often uses, you should use the safe call operator where you access the property:

btnProceed?.setOnClickListener { ... }

如果 btnProceed 是非空值,这将进行常规调用,否则不执行任何操作.

This will make a regular call if btnProceed is a non-null value, and do nothing otherwise.

最后一点,您可以查看 Kotlin Android 扩展,其中如果它适用于您的项目,则无需为您的 View 创建属性.

On a final note, you can check out Kotlin Android Extensions, which eliminates the need to create properties for your Views altogether, if it works for your project.

最后一次编辑(目前):您还应该考虑使用 lazy,如 other 答案.懒惰很酷.

Last edit (for now): you should also look at using lazy as described in the other answers. Being lazy is cool.

这篇关于使用 Kotlin 在 android 中的 UI 组件上声明的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆