android– 尝试访问Kotlin片段中的视图时出现NullPointerException

android– 尝试访问Kotlin片段中的视图时出现NullPointerException,第1张

概述如何使用KotlinAndroidExtensionswithFragments?如果我在onCreateView()中使用它们,我会得到这个NullPointerException异常:Causedby:java.lang.NullPointerException:Attempttoinvokevirtualmethod‘android.view.Viewandroid.view.View.findViewById(int)’on

如何使用Kotlin Android Extensions with Fragments?
如果我在onCreateVIEw()中使用它们,我会得到这个NullPointerException异常:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method ‘androID.vIEw.VIEw androID.vIEw.VIEw.findVIEwByID(int)’ on a
null object reference

这是片段代码:

package com.obaIEd.testrun.Fragmentimport androID.os.Bundleimport androID.support.v4.app.Fragmentimport androID.util.Logimport androID.vIEw.LayoutInflaterimport androID.vIEw.VIEwimport androID.vIEw.VIEwGroupimport com.obaIEd.acaan.Rimport kotlinx.androID.synthetic.main.fragment_card_selector.*public class CardSelectorFragment : Fragment() {    val TAG = javaClass.canonicalname    companion object {        fun newInstance(): CardSelectorFragment {            return CardSelectorFragment()        }    }    overrIDe fun onCreateVIEw(inflater: LayoutInflater?, container: VIEwGroup?, savedInstanceState: Bundle?): VIEw? {        var rootVIEw = inflater?.inflate(R.layout.fragment_card_selector, container, false)        btn_K.setonClickListener { Log.d(TAG, "onVIEwCreated(): hello world"); }        return rootVIEw    }}`

解决方法:

Kotlin合成属性不是神奇的,并且以非常简单的方式工作.当你访问btn_K时,它会调用getVIEw().findVIEwByID(R.ID.btn_K).

问题是您过早访问它. getVIEw()在onCreateVIEw中返回null.尝试在onVIEwCreated方法中执行此 *** 作:

overrIDe fun onVIEwCreated(vIEw: VIEw, savedInstanceState: Bundle?) {    btn_K.setonClickListener { Log.d(TAG, "onVIEwCreated(): hello world"); }}
总结

以上是内存溢出为你收集整理的android – 尝试访问Kotlin片段中的视图时出现NullPointerException全部内容,希望文章能够帮你解决android – 尝试访问Kotlin片段中的视图时出现NullPointerException所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1103557.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-28
下一篇2022-05-28

发表评论

登录后才能评论

评论列表(0条)

    保存