如何在onclick事件之前停止计时器并在onclick事件之后启动

时间:2016-08-29 04:07:26

标签: android android-mediaplayer onclicklistener

如何在onclick事件之前停止计时器并在onclick事件之后启动?按钮点击事件完成后应调用StartTimer()函数但在单击按钮后它不起作用。如何解决这个问题?这是我的代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_words);
    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            if(!test){
                sp.playMusic();
                test = true;
            }
            else{
                sp.playMusic1();
                test = false;
            }
        }
    }, 0, 7000);

    txtone = (ImageView)findViewById(R.id.imageView);
    txttwo = (ImageView)findViewById(R.id.imageView2);
    txtone.setOnClickListener(this);
    txttwo.setOnClickListener(this);

    @Override
    public void onClick(View v)
    {
        switch(v.getId())
        {
            case R.id.imageView:
                txtone.setEnabled(false);
                txttwo.setEnabled(false);
                txtone.setVisibility(View.INVISIBLE);
                timer.cancel();
                if(!test){
                    sp.playMusic();
                    test = true;
                }
                else{
                    sp.playMusic1();
                    test = false;
                }
                sp.playSFXWrong();
                sp.getSFXWrong().setOnCompletionListener
                        (new         MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                txttwo.setEnabled(true);
                            }
                        });
                answer=false;
            case R.id.imageView2:
                txtone.setEnabled(false);
                txttwo.setEnabled(false);
                txttwo.setVisibility(View.INVISIBLE);
                timer.cancel();
                if(!test){
                    sp.playMusic();
                    test = true;
                }
                else{
                    sp.playMusic1();
                    test = false;
                }
                sp.playSFXWrong();
                sp.getSFXWrong().setOnCompletionListener
                        (new
                                 MediaPlayer.OnCompletionListener()
                                 {
                                     @Override
                                     public void onCompletion(MediaPlayer mp)
                                     txttwo.setEnabled(true); } });
                answer=true;
                break;
            }
}

0 个答案:

没有答案