如何使用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.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
}
}
`
解决方法:
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"); }
}