Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

java - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...