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

查看:80
本文介绍了使用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函数时需要添加! sign:

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.

否则,如果您希望编译器保证为您提供安全访问,默认情况下,转换器可以使按钮为空。而不是不安全的 !! operator ,你应该使用安全通话运营商

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 Extensions ,无需为 View <创建属性/ code> s,如果它适用于您的项目。

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 tackoverflow.com/a/44286021/4465208> 其他 答案 。懒惰很酷。

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天全站免登陆