尝试访问Kotlin片段中的视图时发生NullPointerException [英] NullPointerException when trying to access views in a Kotlin fragment
问题描述
如何在Fragment
s上使用Kotlin Android扩展?
如果在onCreateView()
中使用它们,则会出现此NullPointerException
异常:
How to use Kotlin Android Extensions with Fragment
s?
If I use them inside onCreateView()
, I get this NullPointerException
exception:
由于:java.lang.NullPointerException:尝试调用虚拟 方法'android.view.View android.view.View.findViewById(int)'在 空对象引用
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.Fragment
import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.obaied.acaan.R
import 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
}
}
`
推荐答案
科特林合成属性不是魔术,而是以非常简单的方式起作用的.当您访问btn_K
时,它会调用getView().findViewById(R.id.btn_K)
.
Kotlin synthetic properties are not magic and work in a very simple way. When you access btn_K
, it calls for getView().findViewById(R.id.btn_K)
.
问题是您访问它的时间太早. getView()
返回onCreateView
中的null
.尝试使用onViewCreated
方法:
The problem is that you are accessing it too soon. getView()
returns null
in onCreateView
. Try doing it in the onViewCreated
method:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
btn_K.setOnClickListener { Log.d(TAG, "onViewCreated(): hello world"); }
}
这篇关于尝试访问Kotlin片段中的视图时发生NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!