Imagebutton change programmatically?

前端 未结 5 1961
天命终不由人
天命终不由人 2021-02-11 12:21

I\'m trying to change the image of the ImageButton programmatically.

I\'m trying to copy this code, but the setBackgroundDrawable is already deprecated.

         


        
相关标签:
5条回答
  • 2021-02-11 12:28

    your code is trying to change the background of the button. not its image. Those are two different things

      ((ImageButton) view).setImageResource(R.drawable.icon2);
    
    0 讨论(0)
  • 2021-02-11 12:30

    Just try out this way:

    ((ImageButton) view).setImageDrawable(replacer);

    0 讨论(0)
  • 2021-02-11 12:30

    Using Kotlin, you can do this:

    val myImageButton = ImageButton(context).apply({
        background = null
        setImageDrawable(ContextCompat.getDrawable(context, 
                             R.drawable.ic_save_black_24px))
    })
    
    0 讨论(0)
  • 2021-02-11 12:42

    Try this its working for me,Change the background image programmatically,

     image.setBackgroundResource(R.drawable.ico);
    
    0 讨论(0)
  • 2021-02-11 12:49

    Hi you can use the following code

    if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN ) 
    {
        ((ImageButton) view).setImageResource(getResources().getIdentifier("icon2", "drawable", getPackageName()));
    }
    else 
    {
        ((ImageButton) view).setImageDrawable(getDrawable(getResources().getIdentifier("icon2", "drawable", getPackageName())));
    }
    

    Hope this will help you.

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