我正在尝试使用kotlin for android并试图像这样声明Linearlayout:
internal var linlay_SuccessfulPayment : LinearLayout = null!!
internal var linlay_failPayment : LinearLayout
linlay_SuccessfulPayment = findViewById(R.id.linlay_SuccessfulPayment) as LinearLayout
linlay_failPayment = findViewById(R.id.linlay_failPayment) as LinearLayout
但是在日志中我得到了这个:
Caused by: kotlin.KotlinNullPointerException
at com.example.activities.PaymentResult.<init>(Result.kt:14)
at java.lang.class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1096)
at android.app.ActivityThread.performlaunchActivity(ActivityThread.java:3122)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7329)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
请帮帮我.
解决方法:
您的问题是可空性,这将是使用lateinit关键字(documentation)的好地方:
private lateinit var linlay_SuccessfulPayment: LinearLayout
private lateinit var linlay_failPayment: LinearLayout
这样,您可以定义一个不可为空的var,但会延迟初始化,您可以在onCreate()中执行此操作.
您必须在访问它之前初始化它,否则您将获得PropertynotinitialisedException.
第二种选择是使用property delegation进行延迟初始化:
private var linlay_SuccessfulPayment: LinearLayout by Delegates.lazy { findViewById(R.id.linlay_SuccessfulPayment) as LinearLayout }
这样,视图仅在第一次使用时初始化,并且您将所有内容放在一个位置.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。