Search code examples
androidkotlinandroid-drawableimagebutton

Android (Kotlin): Change Background of an ImageButton in a function


Question: How can I declare the ImageButton public, like in Java:

public class MainActivity extends AppCompatActivity {

    ImageButton b1;

Problem: This code works as expected:

override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
   val b1 = findViewById<ImageButton>(R.id.btn_switch) as ImageButton
   b1.setBackgroundResource(R.drawable.switch_gray)`

Within a public fun outside onCreate{} the same code crashes my app:

private fun myfunction(it: String?) {
        if (output == "false") { findViewById<ImageButton>(R.id.btn_switch).setBackgroundResource(R.drawable.switch_red)  }

Solution

  • You can create variable for ImageButton about the onCreate() method, within the class

    private lateinit var b1: ImageButton
    

    This code was equivalent to ImageButton b1; this Java code.

    later on you can initialize that ImageButton in onCreate and use it anywhere within the class.