Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imagebutton change programmatically?

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"/>
like image 259
newbie Avatar asked Jan 09 '13 10:01

newbie


3 Answers

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);
like image 58
Budius Avatar answered Nov 18 '22 02:11

Budius


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

 image.setBackgroundResource(R.drawable.ico);
like image 38
MuraliGanesan Avatar answered Nov 18 '22 01:11

MuraliGanesan


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.

like image 3
ziniestro Avatar answered Nov 18 '22 01:11

ziniestro