找到你要的答案

Q:Assign an image resource to ImageView according to a flag

Q:分配图像资源ImageView根据国旗

I have to change the image dsiplayed in the ImageView, when user click on it. And when he clicks it again, I want to show the original image. How to do this with the flags?

Supposably:

imageView1, R.drawable.pic_one, R.drawable.pic_two.

我要改变形象dsiplayed在ImageView中,当用户点击它。当他再次点击,我想显示原始图像。用国旗怎么办?

估计:

imageView1, R.drawable.pic_one, R.drawable.pic_two.
answer1: 回答1:

you can use a boolean flag for two states, if you need more, use a byte or int and use the switch-case structure

private boolean tmp;

imageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        tmp = !tmp;
        imageView.setImageResource(tmp ? R.drawable.image1 : R.drawable.image2);
   }
 });

你可以使用一个布尔标志为两种状态,如果你需要更多的,使用一个字节或int和使用开关盒结构

private boolean tmp;

imageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        tmp = !tmp;
        imageView.setImageResource(tmp ? R.drawable.image1 : R.drawable.image2);
   }
 });
answer2: 回答2:

I would suggest you to use selector for selected state and then following code.

sample code:

imageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
      imageView.setSelected(!imageView.isSelected());
   }
});

我建议您使用选择器选择的状态,然后按照下列代码。

示例代码:

imageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
      imageView.setSelected(!imageView.isSelected());
   }
});
android  onclick  imageview  flags