androidkotlinandroid-imagebutton

how to set an image to ImageButton background programmatically


I'm coding with Kotlin for Android app. I need to add an image for ImageButton background. I tried ImageButton.setBackgroudResource and ImageButton.setImageResource methods but it would not change.

My code is here:

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setContentView(R.layout.activity_main)
        var imageButton1 = binding.imageButton1
        imageButton1.setBackgroundResource(R.drawable.myImage)
}}

imageButton1.setBackgroundResource(R.drawable.myImage) would not set myImage.png to imageButton1.


Solution

  • Use setImageDrawable and get the drawable from the resources like below

    imageButton1.setImageDrawable(resources.getDrawable(R.drawable.myImage));
    

    or

    imageButton1.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.myImage));