Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android imageview.setBackgroundResource() doesn't work

I have an imageview that should be changed on click

public class Settings extends Activity implements OnClickListener
{
     private ImageView im1;
     @Override
     public void onCreate(Bundle savedInstanceState)
     {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.settings);
         im1 = (ImageView) findViewById( R.id.imageView1 );
         im1.setOnClickListener(this);
     }
     @Override
     public void onClick(View v)
     {
         // TODO Auto-generated method stub
         if (v == im1 )
         {
             Log.d("test", "hey!");
             v.setBackgroundResource(R.drawable.img1);
         }
     }
}

when clicked the method runs and prints out "hey!" but the image won't change?

EDIT: forgot to mention that imageview contains another image provided by xml layout file

like image 791
Ahmad Dwaik 'Warlock' Avatar asked Dec 21 '11 16:12

Ahmad Dwaik 'Warlock'


4 Answers

By convention, you should be using setImageResource(R.drawable.img1); (or setImageDrawable(getResources().getDrawable(R.drawable.img1));) instead of setBackgroundResource(R.drawable.img1);.

like image 53
Chris Cashwell Avatar answered Nov 20 '22 13:11

Chris Cashwell


  ImageView i = (ImageView) findViewById( R.id.imageView1 );
  i.setImageResource(R.id.logo);

   or

  i.setBackgroundResource(R.drawable.icon);
like image 3
selvaiyyamperumal Avatar answered Nov 20 '22 14:11

selvaiyyamperumal


UPDATE

Now, you can use like below,

imageView.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.img1));
like image 2
Amit Vaghela Avatar answered Nov 20 '22 14:11

Amit Vaghela


Try This In API 25

imgSchedule.setImageDrawable(getResources().getDrawable(R.drawable.circle_image_selected));
like image 1
chirag khandla Avatar answered Nov 20 '22 13:11

chirag khandla