如何点击多个imageview

时间:2013-11-30 13:54:20

标签: android imageview onclicklistener

您好我是Android开发的新手。所以我尝试了这种编码,当我点击图像视图时,它将变为另一个图像。而且它运作完美。但我有10个imageview。每次点击图像时,它都会变为另一个图像。是否有更简单的代码可用于10 imageview?我该怎么做?谢谢:))

package com.example.subtraction;


import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

public class Level_1 extends Activity {
private ImageView imageOne=null;
private ImageView imageTwo=null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_level_1);

    imageOne = (ImageView)findViewById(R.id.image);
    imageTwo = (ImageView)findViewById(R.id.newImage);

    imageOne.setOnClickListener(new OnClickListener()
    {
        public void onClick (View view)
        {
            imageTwo.setVisibility(View.VISIBLE);
            view.setVisibility(View.GONE);
        }
    });

    imageTwo.setOnClickListener(new OnClickListener()
    {
        public void onClick(View view)
        {
            imageOne.setVisibility(View.VISIBLE);
            view.setVisibility(View.GONE);
        }
    });
}
}

1 个答案:

答案 0 :(得分:1)

您可以使用单个OnClickListener并将10个ImageView对象放入数组中。像这样:

package com.example.subtraction;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

public class Level_1 extends Activity {
    private ImageView[] images = new ImageView[2];

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_level_1);

        images[0] = (ImageView) findViewById(R.id.image1);
        images[1] = (ImageView) findViewById(R.id.image2);

        for (int i = 0; i < images.length; i++) {
            images[i].setOnClickListener(mOnClickListener);
        }
    }

    private final OnClickListener mOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            for (int i = 0; i < images.length; i++) {
                if (v != images[i]) {
                    images[i].setVisibility(View.VISIBLE);
                }
            }
            v.setVisibility(View.GONE);
        }
    };
}