繁体   English   中英

kotlin findViewById 返回 null

[英]kotlin findViewById returns null

我有以下代码,在单击按钮 findViewById 后返回 null 但是当我设置图片本身的 onclick 属性来更改图片时,没有返回 null 异常。

此代码返回 null 异常:

private lateinit var imageView1: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}

fun change(view: View){
    try {
        imageView1 = view.findViewById(R.id.imageView)
        imageView1.setImageResource(R.drawable.ic_launcher_foreground)
    }
    catch (e: Exception){
        Log.d("errors","first")
    }
}

 <ImageView
        android:id="@+id/imageView"
        android:layout_width="430dp"
        android:layout_height="487dp"
        app:srcCompat="@drawable/lion"
        tools:layout_editor_absoluteX="-22dp"
        tools:layout_editor_absoluteY="-9dp" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="change"
        android:text="change"
        tools:layout_editor_absoluteX="157dp"
        tools:layout_editor_absoluteY="667dp" />

此代码不返回 null 异常并且图片发生变化,此代码中仅更改了 xml 部分,而 Kotlin 部分与上一部分相同:

<ImageView
        android:id="@+id/imageView"
        android:layout_width="430dp"
        android:layout_height="487dp"
        app:srcCompat="@drawable/lion"
        android:onClick="change"
        tools:layout_editor_absoluteX="-22dp"
        tools:layout_editor_absoluteY="-9dp" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="change"
        tools:layout_editor_absoluteX="157dp"
        tools:layout_editor_absoluteY="667dp" />

当你做

imageView1 = view.findViewById(R.id.imageView)

您正在寻找单击按钮所具有的任何子项中的视图。 你只需要做

imageView1 = findViewById(R.id.imageView)

修改change方法后试试这段代码

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}

fun change(view: View){
    when(view.id){
       R.id.imageView -> (view as ImageView).setImageResource(R.drawable.ic_launcher_foreground)
       R.id.button -> (view as Button).text = "Clicked"
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM