Android让ImageView点击后换成另外一张图片

时间:2022-11-29 10:18:13

给ImageView设置点击监听,当点击了,换图片

public class Test extends Activity {
    ImageView iv;
    boolean isChanged = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         iv = (ImageView)findViewById(R.id.imageView1);
        iv.setOnClickListener(new View.OnClickListener() {
             
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(v == iv)
                {
                    if(isChanged){
                        iv.setImageDrawable(getResources().getDrawable(R.drawable.icon));
                    }else
                    {
                        iv.setImageDrawable(getResources().getDrawable(R.drawable.png1));
                    }
                    isChanged = !isChanged;
                     
                }
            }
        });
    }
}