2016-06-10 58 views
0

当我比较duration2duration4的值时,我正在使用的Toast消息将打印两次,但答案/消息是正确的。我不知道为什么会发生。请告诉我如何解决这个问题。为什么吐司消息要打印两次?

Button b1, b2, b3; 
long duration, duration2, duration3, duration4; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    b1=(Button)findViewById(R.id.button1); 
    b2=(Button)findViewById(R.id.button2); 
    b3=(Button)findViewById(R.id.button3); 

    b1.setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      if(event.getAction()==MotionEvent.ACTION_DOWN) { 
       duration=System.currentTimeMillis(); 
      } 
      else if (event.getAction()==MotionEvent.ACTION_UP) { 
       duration2= System.currentTimeMillis()-duration; 
      } 

      return true; 
     } 
    }); 
    b2.setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      if(event.getAction()==MotionEvent.ACTION_DOWN) { 
       duration3=System.currentTimeMillis(); 
      } 
      else if (event.getAction()==MotionEvent.ACTION_UP) { 
       duration4= System.currentTimeMillis()-duration3; 
      } 

      if(duration4<duration2) { 
       Toast.makeText(getApplicationContext(), "Good", Toast.LENGTH_SHORT).show(); 
      } 
      else if(duration4>duration2) { 
       Toast.makeText(getApplicationContext(), "Too Slow Man", Toast.LENGTH_SHORT).show(); 
      } 
      return true; 

     } 
    }); 
} 

回答

0

因为您在onTouchEvent内部烘烤。有一个ACTION_DOWN和一个ACTION_UP。

我想一个简单的解决将是存储一个布尔值说你已经证明消息已经并添加到,如果周围的持续时间语句检查

+0

香港乐施会,会尝试这感谢。 –