How do I programmatically change the ImageButton src target when a condition is met?

后端 未结 3 981
礼貌的吻别
礼貌的吻别 2021-02-19 04:32

I have a school project where I am trying to get a flashlight app going. For the on/off ImageButton, I want to have 4 custom images.

If flashlight is off: -turn_on.png (

相关标签:
3条回答
  • 2021-02-19 04:55

    When setting the image using the following attribute:

    android:src="@drawable/on_selector"

    You will need to use the following to change the image dynamically:

    ImageButton myButton = (ImageButton) findViewById(R.id.my_button);
    myButton.setImageResource(R.drawable.my_button_image);
    
    0 讨论(0)
  • 2021-02-19 04:56

    Is it a requirement that it has to be imageResource? You can try using backgroundResource instead.

    ImageButton flashButtonOn = (ImageButton) findViewById(R.id.flashButtonOn);
    flashButtonOn.setBackgroundResource(R.drawable.on_selector);
    

    Or try

    flashButtonOn.setImageResource(R.drawable.replacementGraphic);
    
    0 讨论(0)
  • 2021-02-19 05:04

    It should be "setImageResource", "setBackgroundResource" changes the background, not the src. btn_MyButton.setImageResource(R.drawable.button_bg_selector_collapsed);

    0 讨论(0)
提交回复
热议问题