Home > other >  kotlin findViewById returns null
kotlin findViewById returns null

Time:06-21

I have the following code which after clicking on the button findViewById returns null but when I set the onclick attribute of the picture itself to change the picture there is no null exception returned.

This code returns null exception:

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" />

This code doesn't return null exception and the picture changes, in this code only the xml part is changed and the Kotlin part is the same as previous part:

<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" />

CodePudding user response:

when you do

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

you are looking for the view within any children that the button clicked has. You need to just do

imageView1 = findViewById(R.id.imageView)

CodePudding user response:

Try this code after modifying the change method

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"
    }
}
  • Related