Imagebutton change programmatically?

▼魔方 西西 提交于 2019-12-04 14:56:34

问题


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

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

public void giveClue(View view) {
    Drawable replacer = getResources().getDrawable(R.drawable.icon2);
    ((ImageButton) view).setEnabled(false);
    ((ImageButton) view).setBackgroundDrawable(replacer);
    gameAdapter.giveClue(game);
}

My button was created using xml as follows:

   <ImageButton
        android:id="@+id/ImageButton2"
        android:layout_width="24dp"
        android:layout_height="22dp"
        android:layout_alignTop="@+id/imageButton1"
        android:layout_toLeftOf="@+id/ImageButton3"
        android:src="@drawable/icon" 
        android:onClick="giveClue"/>

Please help.

Thank you.


回答1:


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);



回答2:


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

 image.setBackgroundResource(R.drawable.ico);



回答3:


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.




回答4:


Just try out this way:

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




回答5:


Using Kotlin, you can do this:

val myImageButton = ImageButton(context).apply({
    background = null
    setImageDrawable(ContextCompat.getDrawable(context, 
                         R.drawable.ic_save_black_24px))
})



回答6:


For kotlin this works for me

yourimagebuttonID.setImageResource(R.drawable.ic_check_black_24dp)



回答7:


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



来源:https://stackoverflow.com/questions/14233062/imagebutton-change-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!