定义全局 android.widget var/val 时的 \\”lateinit\\” 或 \\”by lazy\\” | 珊瑚贝

“lateinit” or “by lazy” when defining global android.widget var/val


当定义一个全局 android.widget 变量时,例如TextView,使用 lateinit 还是 by lazy 更可取?我最初认为使用 by lazy 会是首选,因为它是不可变的,但我不完全

by lazy 示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class MainActivity: AppCompatActivity() {

    val helloWorldTextView by lazy { findViewById(R.id.helloWorldTextView) as TextView }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        updateTextView(helloWorldTextView)
    }

    fun updateTextView(tv: TextView?) {
        tv?.setText(“Hello?”)
    }
}

lateinit 示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class MainActivity: AppCompatActivity() {

    lateinit var helloWorldTextView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        helloWorldTextView = findViewById(R.id.helloWorldTextView) as TextView
        updateTextView(helloWorldTextView)
    }

    fun updateTextView(tv: TextView?) {
        tv?.setText(“Hello?”)
    }
}

在定义全局 android.widget var/val 时,使用其中一个有什么好处?使用 by lazy 定义 android.widget val 是否有任何陷阱?该决定是否仅基于您想要一个可变值还是不可变值?


by lazy 有一个陷阱。小部件属性将是只读的,因此在技术上是最终的(在 Java 术语中)。但是没有文档保证 onCreate() 只为一个实例调用一次。 findViewById() 也可以返回 null.

所以使用 lateinit 是更可取的,你会得到一个异常告诉你 val 是否在 onCreate() 之前使用。

第三种可能性是 Android 综合属性。那你就完全不用担心变量了。

1
2
3
import kotlinx.android.synthetic.main.activity_main.*

helloWorldTextView.text =”Hello?”

  • 这些都是很好的观点。还有,哇!这个扩展是惊人的。感谢您将其包含在您的答案中。
  • onCreate(…) 确实每个 Activity 实例调用一次,但 lazy 委托并不绑定到它,它只是在第一次调用时初始化,在这种情况下完全可以。当然,合成属性无论如何都更容易
  • lazy 也可能导致 Fragment 的 bignerdranch.com/blog/kotlin-when-to-use-lazy-or-lateinit 中的内存泄漏


来源:https://www.codenong.com/44056988/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_8966.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?