Android:如何检查是否正确按下了随机数组中的按钮

时间:2014-04-18 13:31:26

标签: android button random

我需要在android上设计一个有6个按钮的活动,除了其中一个按钮之外的所有按钮都以相同的图标开始。不是随机选择的,并且在一定时间之后,将奇数输出掩盖为与其余部分相同。然后,用户必须识别奇数,并且如果它们是正确的,则重放活动。如果他们错了,那就需要完成。

我已设法创建活动,以便除了选择错误的按钮之外,它还可以识别以上所有内容,如果是,则完成活动。据我所知,问题来自于更改按钮随机选择的事实,因此在程序运行之前我无法确定哪个按钮是错误的按钮。下面是我到目前为止的代码:

ImageButton changedButton;
Random random = new Random();

int changedButtonNo;
int buttonSelect;

int usual = R.drawable.abc_ic_cab_done_holo_light;
int changed = R.drawable.abc_ic_cab_done_holo_dark;

int[] buttons = { R.id.imageButton1, R.id.imageButton2, R.id.imageButton3,    R.id.imageButton4, R.id.imageButton5, R.id.imageButton6 };

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

    buttonSelect = random.nextInt(6);
    changedButtonNo = buttons[buttonSelect];
    changedButton = (ImageButton)findViewById(changedButtonNo);
    changedButton.setImageResource(changed);

    //Decrease amount of time the stimuli is displayed over attempts
    CountDown(60);

    changedButton.setOnTouchListener(new OnTouchListener() 
    {
        public boolean onTouch(View v, MotionEvent event) 
        {
            if (event.getAction() == MotionEvent.ACTION_UP) 
            {
                final Toast toast = Toast.makeText(getBaseContext(), "Correct", Toast.LENGTH_SHORT);
                toast.show();
                recreate();
            }
            return true;
        }
    });
    //If any other button from the list is pressed, exit activity
}

public void CountDown(int milliseconds)
{
    new CountDownTimer(milliseconds, 1000)
    {
        @Override public void onTick(long toFinish)
        {
        }

        @Override public void onFinish()
        {
            changedButton.setImageResource(usual);
        }
    }.start();
}

@Override
public void recreate()
{
    Intent intent = getIntent();
    overridePendingTransition(0, 0);
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    finish();
    overridePendingTransition(0, 0);
    startActivity(intent);
}
View.OnTouchListener getOnTouch(ImageButton button) 
{
    return new View.OnTouchListener() 
    {
        @Override
        public boolean onTouch(View v, MotionEvent event) 
        {
            if (v.getId() == changedButtonNo)
            {
                if (event.getAction() == MotionEvent.ACTION_UP) 
                {
                    final Toast toast = Toast.makeText(getBaseContext(), "Correct", Toast.LENGTH_SHORT);
                    toast.show();
                    recreate();
                }
            }
            else
            {
                final Toast toast = Toast.makeText(getBaseContext(), "Wrong", Toast.LENGTH_SHORT);
                toast.show();
                finish();
            }
            return true;
        }
    };
}

非常感谢任何帮助。

0 个答案:

没有答案