如何在Click事件上比较ImageView ID?

时间:2017-03-29 12:46:55

标签: java android arrays for-loop equals

我有一套ImageView,其中一些是红色闪烁一段时间,如下所示。

enter image description here

enter image description here

我想这样做,当我点击彩色闪烁的imageViews时它会改变为tic标记,当我点击非闪烁的imageViews时它会改变为十字标记。

我的问题是我目前的代码只有一个图像视图和所有其他图像视图都是交叉标记的。

那么如何使tic标记多个ImageView。

这是我的代码:

  org_id = new int[]{R.id.img1_1, R.id.img1_2, R.id.img1_3, R.id.img1_4};

        all = new int[]{R.id.img1_1, R.id.img1_2, R.id.img1_3, R.id.img1_4};




        Random random = new Random();
        for(int j=0;j<2;j++) {
            id = all[random.nextInt(all.length)];


            ObjectAnimator animator = ObjectAnimator.ofInt(findViewById(id), "backgroundResource", R.drawable.new_stateimg, R.drawable.org_state).setDuration(2000);
            Toast.makeText(Game.this, "index" + findViewById(id), Toast.LENGTH_LONG).show();
            animator.setEvaluator(new ArgbEvaluator());
            animator.start();

        for (int i=0; i < org_id.length; ++i) {
            final int btn = org_id[i];

            findViewById(btn).setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    if ((findViewById(id)).equals(findViewById(btn)))
                    {
                        findViewById(id).setBackgroundResource(R.drawable.correct);

                    } else {
                        Toast.makeText(Game.this, "wrong", Toast.LENGTH_SHORT).show();
                        findViewById(btn).setBackgroundResource(R.drawable.cross);

                    }

                }
            });
        }
        }

1 个答案:

答案 0 :(得分:0)

比较你的身份

    if (id.getId() == btn.getId())

在您的代码中执行此操作。

     public void onClick(View view) {
             ImageView imgView = (ImageView)view; //edited
             if(imgView.getDrawable().getConstantState().equals
        (getResources().getDrawable(R.drawable.correct).getConstantState()))
             imgView.setBackgroundResource(R.drawable.incorrect);//set here you incorrect image which you want.

            else 
                imgView.setBackgroundResource(R.drawable.correct);//set here your correct image

  }