如何使用kotlin在android中初始化小部件

sas*_*uke 2 android nullpointerexception kotlin kotlin-android-extensions

我已经开始学习在android中使用kotlin语言并在初始化我的按钮变量时遇到问题,因为在定义我的变量时,它要求在使用null值初始化时给出一些初始值并在oncreate函数中绑定变量

kotlin.KotlinNullPointerException

这是我的代码

class AddsFragment : Fragment() {

    var Add: Button = null!!

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val Rootview = inflater!!.inflate(R.layout.clubsfragment, null, false)
        Add = Rootview.findViewById(R.id.add) as Button
        return Rootview
    }
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ael 16

!!运营商检查接收机null,如果它抛出KotlinNullPointerException.所以null!!总会抛出异常.

您可以通过以下方式实现您的目标:

  1. 将属性的类型设置为Button?.在这种情况下,当访问按钮的方法时,您将不得不使用?!!.

    var add: Button? = null
    // Initialize it somewhere.
    
    add?.setText("Text") // Calls setText if Add != null
    add!!.setText("Text") // Throws an exception if Add == null
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使按钮成为lateinit属性.

    lateinit var add: Button
    
    Run Code Online (Sandbox Code Playgroud)
  3. 使按钮成为notNull委托属性.

    var add: Button by Delegates.notNull()
    
    Run Code Online (Sandbox Code Playgroud)

在最后两种情况下,您无法检查按钮是否null.如果需要null比较工作变量使用第一种方法.


还有另一种方法,我不打算在这个答案中详细描述.第一个是使用Kotlin Android Extensions.这是一个编译器插件,可以为您的视图生成合成属性,因此您无需调用findViewById()并可以使用生成的属性访问视图.

第二种方法是创建自己的代表,findViewById()为您服务.它可能看起来像这样:

val add: Button by bindView(R.id.add)
Run Code Online (Sandbox Code Playgroud)

您可以在KotterKnife项目中找到此类委托的示例.